package cn.jh.clearing.service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import cn.jh.clearing.business.CoinRecordBusiness;
import cn.jh.clearing.business.DistributionBusiness;
import cn.jh.clearing.business.PaymentOrderBusiness;
import cn.jh.clearing.business.ProfitRecordBusiness;
import cn.jh.clearing.pojo.CoinRecord;
import cn.jh.clearing.pojo.DistributionRecord;
import cn.jh.clearing.pojo.PaymentOrder;
import cn.jh.clearing.pojo.PaymentOrderExcel;
import cn.jh.clearing.pojo.PaymentOrderNumber;
import cn.jh.clearing.pojo.ProfitRecord;
import cn.jh.clearing.pojo.UserRealtion;
import cn.jh.clearing.util.Digest;
import cn.jh.clearing.util.RestTemplateUtil;
import cn.jh.clearing.util.Util;
import cn.jh.common.tools.ResultWrap;
import cn.jh.common.utils.AuthorizationHandle;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.DownloadExcelUtil;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.RandomUtils;
import cn.jh.common.utils.TokenUtil;
import cn.jh.common.utils.UUIDGenerator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class PaymentService {

	private static final Logger LOG = LoggerFactory.getLogger(PaymentService.class);

	@Autowired
	private PaymentOrderBusiness paymentOrderBusiness;

	@Autowired
	private ProfitRecordBusiness profitRecordBusiness;

	@Autowired
	private DistributionBusiness distributionBusiness;

	@Autowired
	private CoinRecordBusiness coinRecordBusiness;

	@Autowired
	Util util;

	@Autowired
	RestTemplateUtil restTemplateUtil;

	@Autowired
	RestTemplate restTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Value("${schedule-task.on-off}")
	private String scheduleTaskOnOff;

	/** 获取用户的交易明喜 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/{token}")
	public @ResponseBody Object pagePaymentQueryByUserId(HttpServletRequest request,
			@PathVariable("token") String token,
			// 开始时间
			@RequestParam(value = "start_time", required = false) String startTime,
			// 订单号
			@RequestParam(value = "order_code", required = false) String orderCode,
			// 状态
			@RequestParam(value = "status", defaultValue = "-1", required = false) String status,
			// 外放订单号
			@RequestParam(value = "out_order_code", required = false) String outorderCode,
			// 结束时间
			@RequestParam(value = "end_time", required = false) String endTime,
			// **0 充值 1支付 2提现 3退款 */
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		Map<String, Object> map = new HashMap<String, Object>();
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		if (orderCode != null && !orderCode.equals("")) {
			PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, paymentOrder);
		}
		if (outorderCode != null && !outorderCode.equals("")) {
			PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOderByOutOrdercode(orderCode);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, paymentOrder);
		}
		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
		Date StartTimeDate = null;
		if (startTime != null && !startTime.equalsIgnoreCase("")) {
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null;

		if (endTime != null && !endTime.equalsIgnoreCase("")) {
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}
		String[] str1 = status.split(",");
		if (status == null || status.equals("") || str1.length == 0) {
			str1 = null;
		}
		if (status.equals("-1")) {
			map.put(CommonConstants.RESULT,
					paymentOrderBusiness.queryPaymentOrderByUserid(userId, type, StartTimeDate, endTimeDate, pageable));
		} else {
			map.put(CommonConstants.RESULT, paymentOrderBusiness.queryAllPaymentOrder(userId + "", type, str1,
					StartTimeDate, endTimeDate, pageable));
		}

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");

		return map;
	}

	/** 更新第三方的订单号 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/thirdordercode")
	public @ResponseBody Object updatePaymentThirdOrdercde(HttpServletRequest request,
			@RequestParam(value = "order_code") String orderCode,
			@RequestParam(value = "third_code") String thirdcode) {
		Map map = new HashMap();
		paymentOrderBusiness.updateThirdcodeByOrdercode(thirdcode, orderCode);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;

	}

	/** 更新第三方的订单号 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/autoclearing")
	public @ResponseBody Object updateAutoClearing(HttpServletRequest request,
			@RequestParam(value = "order_code") String orderCode,
			@RequestParam(value = "auto_clearing", required = false) String autoclearing) {
		Map<String, Object> map = new HashMap<>();
		if (autoclearing != null && !"".equals(autoclearing)) {
			paymentOrderBusiness.updateAutoClearingByOrdercode(orderCode, autoclearing);
		}
		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);
		map.put(CommonConstants.RESULT, paymentOrder);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;

	}

	/** 根据订单号获取订单对象 */
	/** 获取用户的交易明喜 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/ordercode")
	public @ResponseBody Object queryPaymentOrder(HttpServletRequest request,
			@RequestParam(value = "order_code") String orderCode) {
		Map<String, Object> map = new HashMap<>();
		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);
		if (paymentOrder == null) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PAYMENT_NOT_EXIST);
			map.put(CommonConstants.RESP_MESSAGE, "订单不存在");
			return map;
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, paymentOrder);
			return map;
		}
	}

	/** 根据订单号获取订单对象 */
	/** 获取用户的交易明喜 **/
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/thirdcode")
	public @ResponseBody Object queryPaymentOrderByThirdcode(HttpServletRequest request,
			@RequestParam(value = "third_code") String thirdcode) {
		Map map = new HashMap();

		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderByThirdcode(thirdcode);
		if (paymentOrder == null) {

			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PAYMENT_NOT_EXIST);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, paymentOrder);
			return map;
		}
	}

	/** 根据外放的订单号， 获取订单 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/outordercode")
	public @ResponseBody Object queryPaymentOrderByOutOrdercode(HttpServletRequest request,
			@RequestParam(value = "order_code") String orderCode) {
		Map map = new HashMap();

		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOderByOutOrdercode(orderCode);
		if (paymentOrder == null) {

			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PAYMENT_NOT_EXIST);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			return map;
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, paymentOrder);
			return map;
		}
	}

	// 根据多个条件查询订单信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/all")
	public @ResponseBody Object pageAllPaymentQuery(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "phone", defaultValue = "", required = false) String phone,
			// 订单号
			@RequestParam(value = "order_code", required = false) String order_code,
			// 外放订单号
			@RequestParam(value = "out_order_code", required = false) String outorderCode,
			// 用户编号
			@RequestParam(value = "userid", defaultValue = "0", required = false) long userid,
			// 贴牌id
			@RequestParam(value = "brand_id", defaultValue = "-1", required = false) long brand_id,

			// 等级
			@RequestParam(value = "grade", required = false) String grade,

			// 身份证号
			@RequestParam(value = "idcard", required = false) String idcard,

			// 银行卡号
			@RequestParam(value = "cardNo", required = false) String cardNo,

			/// **0 充值 1支付 2提现 3退款 */
			@RequestParam(value = "type", required = false) String order_type,

			/** 0 待完成 1已成功已结算 2已取消 3待处理 4已成功待结算 */
			@RequestParam(value = "status", defaultValue = "", required = false) String order_status,
			@RequestParam(value = "isDownload", defaultValue = "0", required = false) String isDownload,

			@RequestParam(value = "start_time", required = false) String startTime,
			@RequestParam(value = "end_time", required = false) String endTime,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

		Date StartTimeDate = null;
		if (size > 1000) {
			size = 1000;
		} else if ("1".equals(isDownload)) {
			size = 2000;
		}
		try {
			if (startTime != null && !startTime.trim().equalsIgnoreCase("")) {
				StartTimeDate = DateUtil.getDateFromStr(startTime);
			}
		} catch (Exception e1) {
			LOG.error("startTime转换异常===========================");
			startTime = null;
		}
		Date endTimeDate = null;

		try {
			if (endTime != null && !endTime.trim().equalsIgnoreCase("")) {
				endTimeDate = DateUtil.getDateFromStr(endTime);
			}
		} catch (Exception e) {
			LOG.error("endTime转换异常============================");
			endTime = null;
		}

		List<PaymentOrder> PaymentOrders = new ArrayList<PaymentOrder>();

		Map<String, Object> map = new HashMap<String, Object>();

		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

		// 根据多个条件查询订单信息
		Map queryPaymentOrderAll = paymentOrderBusiness.queryPaymentOrderAll(startTime, endTime, phone, order_code,
				order_type, order_status, brand_id, cardNo, pageable);
		if (queryPaymentOrderAll.containsKey("content")) {
			List<PaymentOrder> list = (List<PaymentOrder>) queryPaymentOrderAll.get("content");
			if (list == null || list.size() == 0 && order_code != null) {
				PaymentOrder paymentOrder = paymentOrderBusiness.findByThirdOrdercode(order_code);
				if (paymentOrder != null) {
					list = new ArrayList<>();
					list.add(paymentOrder);
					queryPaymentOrderAll.put("content", list);
				}
			}
		}

		if ("1".equals(isDownload)) {
			if (queryPaymentOrderAll.containsKey("content")) {
				List<PaymentOrder> list = (List<PaymentOrder>) queryPaymentOrderAll.get("content");
				if (list != null && list.size() > 0) {
					String downloadFile;
					try {
						downloadFile = DownloadExcelUtil.downloadFile(request, response, list, new PaymentOrderExcel());
					} catch (Exception e) {
						e.printStackTrace();
						LOG.error(ExceptionUtil.errInfo(e));
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					}
					if (downloadFile == null) {
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE, "下载失败!");
						return map;
					} else {
						map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
						map.put(CommonConstants.RESP_MESSAGE, "下载成功!");
						map.put(CommonConstants.RESULT, downloadFile);
						return map;
					}
				}
			} else {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "无数据下载");
				return map;
			}
		}

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, queryPaymentOrderAll);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}

	/** 创建或更新支付/充值/订单 */
	/**
	 * 如果选择三级分销产品升级， 那么product_id需要填入三级分销的产品 id realamount手机充值用
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add")
	public @ResponseBody Object addPaymentOrder(HttpServletRequest request,
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "desc", defaultValue = "", required = false) String desc,
			@RequestParam(value = "desc_code", defaultValue = "", required = false) String descCode,
			@RequestParam(value = "notify_url", defaultValue = "", required = false) String notifyUrl,
			@RequestParam(value = "return_url", defaultValue = "", required = false) String returnUrl,
			@RequestParam(value = "out_order_code", defaultValue = "", required = false) String outOrderCode,
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "openid", required = false) String openid,
			@RequestParam(value = "orderCode", required = false) String orderCode,
			@RequestParam(value = "brand_id", required = false, defaultValue = "-1") String brand_id,
			@RequestParam(value = "amount") String amount,
			// 车牌号
			@RequestParam(value = "carNo", required = false) String carNo,
			// 手机充值用的真实
			@RequestParam(value = "realamount", required = false) String realamount,
			// 充值手机号
			@RequestParam(value = "phonebill", required = false) String phonebill,
			@RequestParam(value = "remark", defaultValue = "", required = false) String remark,
			@RequestParam(value = "channel_tag") String channeltag,
			@RequestParam(value = "bank_card", required = false) String bankcard,
			@RequestParam(value = "product_id", required = false) String prodid) {
		Map<String, Object> map = new HashMap<String, Object>();
		RestTemplate restTemplate = new RestTemplate();

		long brandId = -1;
		try {
			brandId = Long.valueOf(brand_id);
		} catch (NumberFormatException e1) {
			brandId = -1;
		}
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/query/phone";

		/** 根据的用户手机号码查询用户的基本信息 */
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("phone", phone);
		requestEntity.add("brandId", brandId + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		long userId;
		long brandid;
		String brandname;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			userId = resultObj.getLong("id");
			brandid = resultObj.getLong("brandId");
			brandname = resultObj.getString("brandname");
		} catch (Exception e) {
			LOG.error("根据手机号查询用户信息失败=============================");
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "根据手机号查询用户信息失败,请确认手机号是否正确!");
			map.put(CommonConstants.RESULT, "根据手机号查询用户信息失败,请确认手机号是否正确!");
			return map;
		}

		/*
		 * uri = util.getServiceUrl("paymentchannel", "error url request!"); url =
		 * uri.toString() + "/v1.0/paymentchannel/route/query";
		 *//** 根据的渠道标识或去渠道的相关信息 *//*
									 * requestEntity = new LinkedMultiValueMap<String, String>();
									 * requestEntity.add("brandcode", brandid+""); requestEntity.add("channel_type",
									 * type); requestEntity.add("channel_tag", channeltag); result =
									 * restTemplate.postForObject(url, requestEntity, String.class); jsonObject =
									 * JSONObject.fromObject(result); String targetChannelTag =
									 * jsonObject.getString("result");
									 */

		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/channel/query";

		PaymentOrder paymentOrder = new PaymentOrder();

		/** 根据的渠道标识或去渠道的相关信息 */
		if (!channeltag.equalsIgnoreCase("JIEFUBAO")) {

			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("channel_tag", channeltag);

			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			long channelId = resultObj.getLong("id");
			String channelName = resultObj.getString("name");
			String channelTag = resultObj.getString("channelTag");
			String channelType = resultObj.getString("channelType");
			String autoclearing = resultObj.getString("autoclearing");
			// 成本费率
			String costRateStr = resultObj.getString("costRate");
			double costRate = Double.valueOf(costRateStr);

			/** 根据用户的信息获取用户的渠道费率 */
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/channel/rate/query/userid";
			/** 根据的渠道标识或去渠道的相关信息 */
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("channel_id", channelId + "");
			requestEntity.add("user_id", userId + "");
			LOG.info("参数================" + requestEntity);

			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================/v1.0/user/channel/rate/query/userid:" + result);
			jsonObject = JSONObject.fromObject(result);

			if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "亲.下单失败,臣妾已经尽力了,请重试!");
				return map;
			}

			resultObj = jsonObject.getJSONObject("result");
			String rate = resultObj.getString("rate");
			double userRate = Double.valueOf(rate);
			// 当用户费率小于成本费率时不生成订单!
			if (!CommonConstants.ORDER_TYPE_WITHDRAW.equalsIgnoreCase(type) && userRate < costRate) {
				LOG.error("用户费率低于成本费率了!!!生成订单失败=============================用户手机号:" + phone);
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "亲.您的费率有异常!请联系您的管理员!!!");
				return map;
			}

			String extraFee = resultObj.getString("extraFee");
			String withdrawFee = resultObj.getString("withdrawFee");
			paymentOrder.setChannelid(channelId);
			paymentOrder.setChannelname(channelName);
			paymentOrder.setChannelTag(channelTag);
			paymentOrder.setOpenid(openid);
			paymentOrder.setBankcard(bankcard);
			/** 默认是不自动清算 */
			paymentOrder.setAutoClearing("0");
			paymentOrder.setRate(new BigDecimal(rate));
			BigDecimal newextraFee = extraFee == null || extraFee.equalsIgnoreCase("")
					|| extraFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(extraFee);
			BigDecimal newwithdrawFee = withdrawFee == null || withdrawFee.equalsIgnoreCase("")
					|| withdrawFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(withdrawFee);

			paymentOrder.setExtraFee(newextraFee.add(newwithdrawFee));
			paymentOrder.setCostfee(newwithdrawFee);
			paymentOrder.setChannelType(channelType);
			/** 充值到账要扣除手续费的 */
			if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {
				BigDecimal fee = new BigDecimal("0.00");
				if ("0".equals(autoclearing.trim())) {
					fee = new BigDecimal(amount).multiply(new BigDecimal(rate));
				} else {
					fee = new BigDecimal(amount).multiply(new BigDecimal(rate)).add(paymentOrder.getExtraFee());
				}
				paymentOrder
						.setRealAmount(new BigDecimal(amount).subtract(fee).setScale(2, BigDecimal.ROUND_HALF_DOWN));
			} else if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_WITHDRAW)) { // 单笔的提现费用
				paymentOrder.setRealAmount(new BigDecimal(amount).subtract(paymentOrder.getExtraFee()).setScale(2,
						BigDecimal.ROUND_HALF_DOWN));

			} else if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {

				/** 扣除通道的手续费.add(paymentOrder.getExtraFee()) */
				BigDecimal fee = new BigDecimal(amount).multiply(new BigDecimal(rate));
				paymentOrder
						.setRealAmount(new BigDecimal(amount).subtract(fee).setScale(2, BigDecimal.ROUND_HALF_DOWN));

			} else if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_REFUND)) {

			} else if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAYMENT)) {
				BigDecimal fee = paymentOrder.getExtraFee();
				paymentOrder
						.setRealAmount(new BigDecimal(amount).subtract(fee).setScale(2, BigDecimal.ROUND_HALF_DOWN));
			}

		} else {
			paymentOrder.setChannelname("JIEFUBAO");
			paymentOrder.setChannelTag("JIEFUBAO");
			paymentOrder.setChannelType("2");
			paymentOrder.setRate(BigDecimal.ZERO);
			paymentOrder.setExtraFee(BigDecimal.ZERO);
			paymentOrder.setRealAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));

		}

		// String withdrawFee = resultObj.getString("withdrawFee");

		paymentOrder.setAmount(new BigDecimal(amount));
		paymentOrder.setUserid(userId);
		paymentOrder.setBrandid(brandid);
		paymentOrder.setBrandname(brandname);
		if (remark == null) {
			paymentOrder.setRemark("");
		} else {
			paymentOrder.setRemark(remark);
		}
		paymentOrder.setCreateTime(new Date());
		paymentOrder.setUpdateTime(new Date());
		paymentOrder.setDesc(desc);
		paymentOrder.setDescCode(descCode);
		if ("YB_PAY".equalsIgnoreCase(channeltag) || "YB_PAY2".equalsIgnoreCase(channeltag)
				|| "YB_QUICK".equals(channeltag)) {
			paymentOrder.setOrdercode(UUIDGenerator.getUUID().substring(0, 20));
		} else if ("CREDICTPAY".equalsIgnoreCase(channeltag)) {
			paymentOrder.setOrdercode(orderCode);
		} else if ( "YH_QUICK".equalsIgnoreCase(channeltag)|| "LD_QUICK".equalsIgnoreCase(channeltag)) {
			paymentOrder.setOrdercode(getNumberOrderCode());
		} else if ("WF_QUICK".equalsIgnoreCase(channeltag)) {
			paymentOrder.setOrdercode(getWFNumberOrderCode());
		} else {
			paymentOrder.setOrdercode(UUIDGenerator.getUUID());
		}

		paymentOrder.setPhone(phone);
		paymentOrder.setOutMerOrdercode(outOrderCode);
		paymentOrder.setType(type);
		paymentOrder.setOutNotifyUrl(notifyUrl);
		paymentOrder.setOutReturnUrl(returnUrl);
		paymentOrder.setStatus(CommonConstants.ORDER_READY);
		// BigDecimal newWithdrawFee = withdrawFee == null ||
		// withdrawFee.equalsIgnoreCase("") ||
		// withdrawFee.equalsIgnoreCase("null")? BigDecimal.ZERO : new
		// BigDecimal(withdrawFee);

		if (prodid != null && !prodid.equalsIgnoreCase("")) {
			paymentOrder.setThirdlevelid(prodid);
		}
		LOG.info("RESULT================" + paymentOrder.getOrdercode() + "************************************");
		paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
		LOG.info("RESULT================" + paymentOrder.toString() + "************************************");
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, paymentOrder);
		return map;

	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add2")
	public @ResponseBody Object addPaymentOrderFirst(HttpServletRequest request,
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "desc", defaultValue = "", required = false) String desc,
			@RequestParam(value = "userId", defaultValue = "", required = false) long userId,
			@RequestParam(value = "bankCard", defaultValue = "", required = false) String bankCard,
			@RequestParam(value = "amount", defaultValue = "", required = false) String amount,
			@RequestParam(value = "orderCode", defaultValue = "", required = false) String orderCode,
			@RequestParam(value = "channel_tag", defaultValue = "", required = false) String channelTag) {
		PaymentOrder paymentOrder = new PaymentOrder();
		paymentOrder.setAmount(new BigDecimal(amount));
		paymentOrder.setType("9");
		paymentOrder.setDesc(desc);
		paymentOrder.setOrdercode(orderCode);
		paymentOrder.setChannelTag(channelTag);
		paymentOrder.setUserid(userId);
		paymentOrder.setBankcard(bankCard);
		paymentOrder.setCreateTime(new Date());
		paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
		LOG.info("RESULT================" + paymentOrder.toString() + "************************************");
		Map map = new HashMap();
		if (null == paymentOrder || "".equals(paymentOrder)) {
			map.put("resp_message", "新增订单失败");
			return map;
		}
		map.put("result", paymentOrder.toString());
		map.put("resp_message", "新增订单成功");
		return map;
	}

	/** 创建或更新支付/充值/订单 */
	/**
	 * 如果选择三级分销产品升级， 那么product_id需要填入三级分销的产品 id realamount手机充值用
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/type1/add")
	public @ResponseBody Object addPaymentOrderType1(HttpServletRequest request,
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "desc", defaultValue = "", required = false) String desc,
			@RequestParam(value = "desc_code", defaultValue = "", required = false) String descCode,
			@RequestParam(value = "notify_url", defaultValue = "", required = false) String notifyUrl,
			@RequestParam(value = "return_url", defaultValue = "", required = false) String returnUrl,
			@RequestParam(value = "out_order_code", defaultValue = "", required = false) String outOrderCode,
			@RequestParam(value = "userid") String userid,
			@RequestParam(value = "openid", required = false) String openid,
			@RequestParam(value = "amount") String amount,
			// 车牌号
			@RequestParam(value = "carNo", required = false) String carNo,
			// 手机充值用的真实
			@RequestParam(value = "realamount", required = false) String realamount,
			// 充值手机号
			@RequestParam(value = "phonebill", required = false) String phonebill,
			@RequestParam(value = "remark", defaultValue = "", required = false) String remark,
			@RequestParam(value = "channel_tag") String channeltag,
			@RequestParam(value = "bank_card", required = false) String bankcard,
			@RequestParam(value = "product_id", required = false) String prodid) {

		RestTemplate restTemplate = new RestTemplate();

		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/query/id";

		/** 根据的用户手机号码查询用户的基本信息 */
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("id", userid);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		long userId = resultObj.getLong("id");
		long brandid = resultObj.getLong("brandId");
		String brandname = resultObj.getString("brandname");
		String phone = resultObj.getString("phone");

		/*
		 * uri = util.getServiceUrl("paymentchannel", "error url request!"); url =
		 * uri.toString() + "/v1.0/paymentchannel/route/query";
		 *//** 根据的渠道标识或去渠道的相关信息 *//*
									 * requestEntity = new LinkedMultiValueMap<String, String>();
									 * requestEntity.add("brandcode", brandid+""); requestEntity.add("channel_type",
									 * type); requestEntity.add("channel_tag", channeltag); result =
									 * restTemplate.postForObject(url, requestEntity, String.class); jsonObject =
									 * JSONObject.fromObject(result); String targetChannelTag =
									 * jsonObject.getString("result");
									 */

		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/channel/query";

		PaymentOrder paymentOrder = new PaymentOrder();

		/** 根据的渠道标识或去渠道的相关信息 */
		if (channeltag.equalsIgnoreCase("JIEFUBAO") && !descCode.equals("RedPayment")) {

			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("channel_tag", channeltag);

			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			long channelId = resultObj.getLong("id");
			String channelName = resultObj.getString("name");
			String channelTag = resultObj.getString("channelTag");
			String channelType = resultObj.getString("channelType");
			/** 根据用户的信息获取用户的渠道费率 */
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

			/** 根据的渠道标识或去渠道的相关信息 */
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("channel_id", channelId + "");
			requestEntity.add("user_id", userId + "");

			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			jsonObject = JSONObject.fromObject(result);

			if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
				Map<String, String> map = new HashMap<String, String>();
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "亲.下单失败,臣妾已经尽力了,请重试!");
				return map;
			}

			resultObj = jsonObject.getJSONObject("result");
			String rate = resultObj.getString("rate");
			String extraFee = resultObj.getString("extraFee");

			paymentOrder.setChannelid(channelId);
			paymentOrder.setChannelname(channelName);
			paymentOrder.setChannelTag(channelTag);
			paymentOrder.setOpenid(openid);
			paymentOrder.setBankcard(bankcard);
			/** 默认是不自动清算 */
			paymentOrder.setAutoClearing("0");
			paymentOrder.setRate(new BigDecimal(rate));
			BigDecimal newextraFee = extraFee == null || extraFee.equalsIgnoreCase("")
					|| extraFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(extraFee);
			paymentOrder.setExtraFee(newextraFee);
			paymentOrder.setChannelType(channelType);
			/** 充值到账要扣除手续费的 */
			if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
				paymentOrder.setRealAmount(realamount != null ? new BigDecimal(realamount) : new BigDecimal(amount));
				paymentOrder.setChannelname("节付宝");
				paymentOrder.setChannelTag("JIEFUBAO");
				paymentOrder.setChannelType("1");
				paymentOrder.setPhoneBill(phonebill != null ? phonebill : "");
				paymentOrder.setCarNo(carNo != null ? carNo : "");
			}
		} else if (descCode.equals("RedPayment")) {

			paymentOrder.setChannelname("JIEFUBAO");
			paymentOrder.setChannelTag("JIEFUBAO");
			paymentOrder.setChannelType("0");
			paymentOrder.setRate(BigDecimal.ZERO);
			paymentOrder.setExtraFee(BigDecimal.ZERO);
			paymentOrder.setRealAmount(new BigDecimal(amount));
		}
		// String withdrawFee = resultObj.getString("withdrawFee");

		paymentOrder.setAmount(new BigDecimal(amount));
		paymentOrder.setUserid(userId);
		paymentOrder.setBrandid(brandid);
		paymentOrder.setBrandname(brandname);
		if (remark == null) {
			paymentOrder.setRemark("");
		} else {
			paymentOrder.setRemark(remark);
		}
		paymentOrder.setCreateTime(new Date());
		paymentOrder.setUpdateTime(new Date());
		paymentOrder.setDesc(desc);
		paymentOrder.setDescCode(descCode);
		paymentOrder.setOrdercode(UUIDGenerator.getUUID());
		paymentOrder.setPhone(phone);
		paymentOrder.setOutMerOrdercode(outOrderCode);
		paymentOrder.setType(type);
		paymentOrder.setOutNotifyUrl(notifyUrl);
		paymentOrder.setOutReturnUrl(returnUrl);
		paymentOrder.setStatus(CommonConstants.ORDER_READY);
		// BigDecimal newWithdrawFee = withdrawFee == null ||
		// withdrawFee.equalsIgnoreCase("") ||
		// withdrawFee.equalsIgnoreCase("null")? BigDecimal.ZERO : new
		// BigDecimal(withdrawFee);

		if (prodid != null && !prodid.equalsIgnoreCase("")) {
			paymentOrder.setThirdlevelid(prodid);
		}

		paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, paymentOrder);
		return map;

	}

	/** 更新用户的订单 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/type1/update")
	public @ResponseBody Object updatePaymentOrderType1(HttpServletRequest request,
			@RequestParam(value = "order_code") String ordercode,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "third_code", required = false) String thirdcode,
			@RequestParam(value = "direct_clearing", required = false, defaultValue = "0") String directclearing) {

		Map<String, Object> resultmap = new HashMap<String, Object>();

		if (status != null && !status.equalsIgnoreCase("")) {

			if (paymentOrderBusiness.queryPaymentOrderBycodeAndStatus(ordercode, status) != null) {
				resultmap.put(CommonConstants.RESP_CODE, CommonConstants.ERRRO_ORDER_HAS_CHECKED);
				resultmap.put(CommonConstants.RESP_MESSAGE, "已经处理");
				return resultmap;
			}

		}

		/** 根据的用户手机号码查询用户的基本信息 */
		PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);

		if (thirdcode != null && !thirdcode.equalsIgnoreCase("")) {
			order.setThirdOrdercode(thirdcode);
		}
		order.setUpdateTime(new Date());

		if (status != null && !status.equalsIgnoreCase("")) {
			order.setStatus(status);
		}

		paymentOrderBusiness.mergePaymentOrder(order);

		/** 提现成功或者提现失败的情况下，都需要将金额首先解冻 */
		if (status != null && !status.equalsIgnoreCase("")
				&& (status.equalsIgnoreCase("1") || status.equalsIgnoreCase("2"))) {

			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {

				if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
					RestTemplate restTemplate = new RestTemplate();
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					URI uri = util.getServiceUrl("user", "error url request!");
					String url = uri.toString() + "/v1.0/user/account/freeze";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("order_code", order.getOrdercode());
					requestEntity.add("user_id", order.getUserid() + "");
					requestEntity.add("amount", order.getRealAmount().toString());
					requestEntity.add("add_or_sub", "1");
					restTemplate.postForObject(url, requestEntity, String.class);

				}

			}

		}

		/** 充值的订单, 要发放分润， 发放积分 */
		if (status != null && !status.equalsIgnoreCase("") && status.equalsIgnoreCase(CommonConstants.ORDER_SUCCESS)) {
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
					|| order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {

				/** 表示是分润提现到余额 */
				if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
					if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
						/** 首先更新用户的账户余额 **/
						/** 如果通道自动清算的就不需要更新用户的账户了 */
						if (order.getAutoClearing().equalsIgnoreCase("0")) {
							RestTemplate restTemplate = new RestTemplate();
							MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
							URI uri = util.getServiceUrl("user", "error url request!");
							String url = uri.toString() + "/v1.0/user/account/update";
							requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("amount", order.getRealAmount().toString());
							requestEntity.add("user_id", order.getUserid() + "");
							requestEntity.add("order_code", order.getOrdercode());

							if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
								/** 提现的时候减钱 */
								requestEntity.add("addorsub", "1");

							}
							restTemplate.postForObject(url, requestEntity, String.class);

							if (order.getDescCode() != null && order.getDescCode().equals("MobilePayment")) {
								restTemplate = new RestTemplate();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
								String result = restTemplate.getForObject(url, String.class);
								JSONObject jsonObject = JSONObject.fromObject(result);
								LOG.info("RESULT================MobilePayment" + result);
								JSONObject resultbrand = jsonObject.getJSONObject("result");
								/******
								 * 添加贴牌的钱
								 *****/
								restTemplate = new RestTemplate();
								requestEntity = new LinkedMultiValueMap<String, String>();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/account/update";
								requestEntity = new LinkedMultiValueMap<String, String>();
								requestEntity.add("amount", order.getRealAmount().toString());
								requestEntity.add("user_id", resultbrand.getString("manageid"));
								requestEntity.add("order_code", order.getOrdercode());
								/** 话费充值的时候向贴牌 */
								requestEntity.add("addorsub", "0");
								restTemplate.postForObject(url, requestEntity, String.class);

							}
						}

					} else if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)) {

						if (order.getDescCode() != null && order.getDescCode().equals("RedPayment")) {

							/****
							 * 检查余额
							 ***/
							RestTemplate restTemplate = new RestTemplate();
							URI uri = util.getServiceUrl("user", "error url request!");
							String url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
							String result = restTemplate.getForObject(url, String.class);
							JSONObject jsonObject = JSONObject.fromObject(result);
							LOG.info("RESULT================purchaseShopping" + result);
							JSONObject resultbrand = jsonObject.getJSONObject("result");

							uri = util.getServiceUrl("user", "error url request!");
							url = uri.toString() + "/v1.0/user/account/query/userId";
							// **根据的用户手机号码查询用户的基本信息*/
							LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("user_id", resultbrand.getString("manageid"));
							restTemplate = new RestTemplate();
							result = restTemplate.postForObject(url, requestEntity, String.class);
							LOG.info("RESULT================purchaseShopping" + result);
							jsonObject = JSONObject.fromObject(result);
							JSONObject UserAccount = jsonObject.getJSONObject("result");
							BigDecimal balance = new BigDecimal("0");
							if (UserAccount.containsKey("balance")) {
								balance = new BigDecimal(UserAccount.getString("balance"));
							}
							if (balance.compareTo(order.getRealAmount()) == -1) {
								resultmap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
								resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
								return resultmap;

							}

							/** 添加用户钱 */
							{
								restTemplate = new RestTemplate();
								requestEntity = new LinkedMultiValueMap<String, String>();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/account/update";
								requestEntity = new LinkedMultiValueMap<String, String>();
								requestEntity.add("amount", order.getRealAmount().toString());
								requestEntity.add("user_id", order.getUserid() + "");
								requestEntity.add("order_code", order.getOrdercode());
								restTemplate.postForObject(url, requestEntity, String.class);
							}

							/******
							 * 减去贴牌的钱
							 *****/
							{
								restTemplate = new RestTemplate();
								requestEntity = new LinkedMultiValueMap<String, String>();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/account/update";
								requestEntity = new LinkedMultiValueMap<String, String>();
								requestEntity.add("amount", order.getRealAmount().toString());
								requestEntity.add("user_id", resultbrand.getString("manageid"));
								requestEntity.add("order_code", order.getOrdercode());
								/** 提现的时候减钱 */
								requestEntity.add("addorsub", "1");
								restTemplate.postForObject(url, requestEntity, String.class);

							}

						}

					}

				}

			}

			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
				/** 循环处理用户的分润 */
				rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
						order.getBrandid());
			}

		}
		resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
		return resultmap;
	}

	/** 更新用户的订单 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/sendrebate")
	public @ResponseBody Object sendRebate(HttpServletRequest request,
			@RequestParam(value = "order_code") String ordercode) {
		Map resultmap = new HashMap();
		/** 根据的用户手机号码查询用户的基本信息 */
		PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
		/** 循环处理用户的分润 */
		rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
				order.getBrandid());
		resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
		return resultmap;

	}

	/** 更新用户的订单 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update")
	public @ResponseBody Object updatePaymentOrder(HttpServletRequest request,
			@RequestParam(value = "order_code") String ordercode,
			@RequestParam(value = "status", required = false) String status,
			@RequestParam(value = "third_code", required = false) String thirdcode,
			@RequestParam(value = "direct_clearing", required = false, defaultValue = "0") String directclearing) {
		Map<String, Object> resultmap = new HashMap<String, Object>();
		LOG.info("/v1.0/transactionclear/payment/update===============" + ordercode);
		if (status != null && !status.equalsIgnoreCase("")) {
			if (paymentOrderBusiness.queryPaymentOrderBycodeAndStatus(ordercode, status) != null) {
				resultmap.put(CommonConstants.RESP_CODE, CommonConstants.ERRRO_ORDER_HAS_CHECKED);
				resultmap.put(CommonConstants.RESP_MESSAGE, "已经处理");
				return resultmap;
			}
		}

		/** 根据的用户手机号码查询用户的基本信息 */
		PaymentOrder order = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
		if (order == null) {
			resultmap.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			resultmap.put(CommonConstants.RESP_MESSAGE, "未获取到该订单!");
			return resultmap;
		}
		
		boolean hasKey = false;
		String key = "/v1.0/transactionclear/payment/update:ordercode=" + ordercode + ";status=" + status + ";thirdcode=" + thirdcode + ";directclearing="+directclearing;
		ValueOperations<String, String> operations = redisTemplate.opsForValue();
		hasKey = redisTemplate.hasKey(key);
		if(hasKey){
			return ResultWrap.init(CommonConstants.ORDER_SUCCESS, "订单处理中");
		}
		operations.set(key, key,30,TimeUnit.SECONDS);
		

		LOG.info("/v1.0/transactionclear/payment/update===============" + order);
		if (thirdcode != null && !thirdcode.equalsIgnoreCase("")) {
			order.setThirdOrdercode(thirdcode);
		}
		order.setUpdateTime(new Date());

		/** 如果状态是成功, 判断交易类型 */
		if (status != null && !"".equalsIgnoreCase(status) && status.equalsIgnoreCase("1")
				&& !order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
				&& !order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_WITHDRAW)) {
			/** 判断通道的结算类型 */
			String clearingType = order.getChannelType();
			if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_T_0)) {
				/** 判断当前是否是休息日 */
				Calendar today = Calendar.getInstance();
				if (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
						|| today.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
					status = "4";
				} else {
					status = "1";
				}
			} else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_T_1)) {
				/** 判断当前是否是休息日 */
				Calendar today = Calendar.getInstance();
				if (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
						|| today.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
					status = "4";
				} else {
					/** 判断当前日期和订单的生成日期是否相隔24小时 */
					int day = getIntervalDays(order.getCreateTime(), today.getTime());
					if (day > 0) {
						status = "1";
					} else {
						status = "4";
					}
				}
			} else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_D_0)) {
				status = "1";
			} else if (clearingType.equalsIgnoreCase(CommonConstants.CLEARING_D_1)) {
				Calendar today = Calendar.getInstance();
				/** 判断当前日期和订单的生成日期是否相隔24小时 */
				int day = getIntervalDays(order.getCreateTime(), today.getTime());
				if (day > 0) {
					status = "1";
				} else {
					status = "4";
				}
			} else {
				status = "1";
			}
		}

		if (status != null && !status.equalsIgnoreCase("")) {
			order.setStatus(status);
		}
		if (status != null && !status.equalsIgnoreCase("") && status.equals("4")) {
			/**
			 * 推送消息 /v1.0/user/jpush/tset
			 */
			String alert = "余额充值";
			String content = "亲爱的会员，" + order.getRealAmount().setScale(2, BigDecimal.ROUND_DOWN) + "元订单已下单成功，等待结算！";
			String btype = "balanceadd";
			String btypeval = "";
			/** 获取身份证实名信息 */
			// URI uri = util.getServiceUrl("user", "error url request!");
			// String url = uri.toString() + "/v1.0/user/jpush/tset";
			String url = "http://user/v1.0/user/jpush/tset";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("userId", order.getUserid() + "");
			requestEntity.add("alert", alert + "");
			requestEntity.add("content", content + "");
			requestEntity.add("btype", btype + "");
			requestEntity.add("btypeval", btypeval + "");
			// RestTemplate restTemplate = new RestTemplate();
			try {
				restTemplate.postForObject(url, requestEntity, String.class);
			} catch (RestClientException e) {
				e.printStackTrace();
				LOG.error(ExceptionUtil.errInfo(e));
			}

		}
		LOG.info("==============ordercode=" + ordercode + "==============status=" + status);
		paymentOrderBusiness.mergePaymentOrder(order);
		/** 提现成功或者提现失败的情况下，都需要将金额首先解冻 */
		if (status != null && !status.equalsIgnoreCase("")
				&& (status.equalsIgnoreCase("1") || status.equalsIgnoreCase("2"))) {
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_WITHDRAW)) {
				if (!order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
					// RestTemplate restTemplate = new RestTemplate();
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					// URI uri = util.getServiceUrl("user", "error url request!");
					// String url = uri.toString() + "/v1.0/user/account/freeze";
					String url = "http://user/v1.0/user/account/freeze";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("order_code", order.getOrdercode());
					requestEntity.add("user_id", order.getUserid() + "");
					requestEntity.add("amount", order.getAmount().toString());
					requestEntity.add("add_or_sub", "1");
					restTemplate.postForObject(url, requestEntity, String.class);

				} else {

					// RestTemplate restTemplate = new RestTemplate();
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					// URI uri = util.getServiceUrl("user", "error url request!");
					// String url = uri.toString() + "/v1.0/user/account/rebate/unfreeze";
					String url = "http://user/v1.0/user/account/rebate/unfreeze";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("order_code", order.getOrdercode());
					requestEntity.add("user_id", order.getUserid() + "");
					requestEntity.add("amount", order.getAmount().toString());
					requestEntity.add("add_or_sub", "1");
					restTemplate.postForObject(url, requestEntity, String.class);
				}
			}
		}

		LOG.info("===============222222222222222222===============是否变更余额判断");
		/** 充值的订单, 要发放分润， 发放积分 */
		if (status != null && !status.equalsIgnoreCase("") && status.equalsIgnoreCase(CommonConstants.ORDER_SUCCESS)) {
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)
					|| order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_WITHDRAW)) {
				/** 表示是分润提现到余额 */
				if (order.getChannelTag().equalsIgnoreCase("JIEFUBAO")) {
					/** 首先更新用户的账户余额 **/
					// RestTemplate restTemplate = new RestTemplate();
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					// URI uri = util.getServiceUrl("user", "error url request!");
					// String url = uri.toString() + "/v1.0/user/account/rebate/update";
					String url = "http://user/v1.0/user/account/rebate/update";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("amount", order.getRealAmount().toString());
					requestEntity.add("user_id", order.getUserid() + "");
					requestEntity.add("order_code", order.getOrdercode());
					restTemplate.postForObject(url, requestEntity, String.class);
				} else {
					/** 首先更新用户的账户余额 **/
					/** 如果通道自动清算的就不需要更新用户的账户了 */
					if (order.getAutoClearing().equalsIgnoreCase("0")) {
						RestTemplate restTemplate = new RestTemplate();
						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
						URI uri = util.getServiceUrl("user", "error url request!");
						String url = uri.toString() + "/v1.0/user/account/update";
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("user_id", order.getUserid() + "");
						requestEntity.add("order_code", order.getOrdercode());
						if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_WITHDRAW)) {
							requestEntity.add("amount", order.getAmount().toString());
							/** 提现的时候减钱 */
							requestEntity.add("addorsub", "1");
						} else {
							requestEntity.add("amount", order.getRealAmount().toString());
						}
						restTemplate.postForObject(url, requestEntity, String.class);
					}
				}
			}

			LOG.info("===============333333333333333333===============是否分润判断");
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)
					|| CommonConstants.ORDER_TYPE_REPAYMENT.equals(order.getType())) {
				/** 循环处理用户的分润 */
				rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
						order.getBrandid());
			}

			/** 如果是支付订单 */
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)&& (order.getDescCode() == null || !order.getDescCode().equals("shopping"))) {
				/** 更新用户的等级 */
				if (order.getThirdlevelid() != null && !order.getThirdlevelid().equalsIgnoreCase("")) {
					/** 获取用户的等级信息 */
					// RestTemplate restTemplate = new RestTemplate();
					// URI uri = util.getServiceUrl("user", "error url request!");
					String url = "http://user/v1.0/user/thirdlevel/prod/query/" + order.getThirdlevelid();
					String result = restTemplate.getForObject(url, String.class);
					JSONObject jsonObject = JSONObject.fromObject(result);
					JSONObject objResObject = jsonObject.getJSONObject("result");
					String grade = objResObject.getString("grade");
					/** 更新用户的等级 **/
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					url = "http://user/v1.0/user/grade/update";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("grade", grade);
					requestEntity.add("id", order.getUserid() + "");
					result = restTemplate.postForObject(url, requestEntity, String.class);
					LOG.info("=====" +order.getPhone()+ "=====升级结果:" + result);
					/*
					 * url = uri.toString() +
					 * "/v1.0/user/thirdlevel/prod/rate/"+order.getThirdlevelid( ); result =
					 * restTemplate.getForObject(url, String.class); jsonObject =
					 * JSONObject.fromObject(result); JSONArray jsonArray =
					 * jsonObject.getJSONArray("result");
					 * 
					 * for(int i=0;i<jsonArray.size();i++){
					 * 
					 *//** 更新用户的费率 *//*
										 * requestEntity = new LinkedMultiValueMap<String, String>(); url =
										 * uri.toString() + "/v1.0/user/channel/rate/update/userid"; requestEntity = new
										 * LinkedMultiValueMap<String, String>(); requestEntity.add("user_id",
										 * order.getUserid()+""); requestEntity.add("channel_id",
										 * jsonArray.optJSONObject(i).optString( "channelId"));
										 * requestEntity.add("rate", jsonArray.optJSONObject(i).optString( "rate"));
										 * result = restTemplate.postForObject(url, requestEntity, String.class);
										 * 
										 * }
										 */
					// restTemplate = new RestTemplate();
					// uri = util.getServiceUrl("user", "error url request!");
					url = "http://user/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
					result = restTemplate.getForObject(url, String.class);
					jsonObject = JSONObject.fromObject(result);

					jsonObject = jsonObject.getJSONObject(CommonConstants.RESULT);
					int isNewRebate = jsonObject.getInt("isNewRebate");
					if (isNewRebate == 0) {
						/** 如果是支付订单，返佣，并且设置用户的刷卡费率 */
						// restTemplate = new RestTemplate();
						// uri = util.getServiceUrl("user", "error url request!");
						url = "http://user/v1.0/user/thirdlevel/ratio/query/" + order.getBrandid();
						result = restTemplate.getForObject(url, String.class);
						jsonObject = JSONObject.fromObject(result);
						JSONArray jsonArray = jsonObject.getJSONArray("result");
						Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
						for (int i = 0; i < jsonArray.size(); i++) {
							map.put(jsonArray.optJSONObject(i).optString("preLevel"),
									new BigDecimal(jsonArray.optJSONObject(i).optString("ratio")));
						}
						/** 计算用户三级返佣 */
						/** 三级分销的金额也是扣除手续费以后的金额 */
						sendThirdDistribution(ordercode, order.getUserid(), order.getPhone(), order.getRealAmount(),
								map, order.getBrandid());
					} else if (isNewRebate == 1) {
						// restTemplate = new RestTemplate();
						// uri = util.getServiceUrl("user", "error url request!");
						url = "http://user/v1.0/user/thirdlevel/ratio/query/by/thirdlevelid";
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("brandId", order.getBrandid() + "");
						requestEntity.add("thirdLevelId", order.getThirdlevelid());
						result = restTemplate.postForObject(url, requestEntity, String.class);
						jsonObject = JSONObject.fromObject(result);
						JSONArray jsonArray = jsonObject.getJSONArray(CommonConstants.RESULT);
						Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
						for (int i = 0; i < jsonArray.size(); i++) {
							map.put(jsonArray.optJSONObject(i).optString("preLevel"),
									new BigDecimal(jsonArray.optJSONObject(i).optString("ratio")));
						}
						sendThirdDistributionNew(ordercode, order.getUserid(), order.getPhone(), order.getRealAmount(),
								map, order.getBrandid(), grade);
					}
				}
			} else if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY) && order.getDescCode() != null
					&& order.getDescCode().equals("shopping")) {
				/** 循环处理用户的分润 */
				rebate(ordercode, order.getUserid(), order.getChannelid(), order.getAmount(), order.getRate(),
						order.getBrandid());
				/*** 转给贴牌商 **/
				{
					/** 通过用户ID判定是否为贴牌 */
					// RestTemplate restTemplate = new RestTemplate();
					// URI uri = util.getServiceUrl("user", "error url request!");
					String url = "http://user/v1.0/user/brand/query/id?brand_id=" + order.getBrandid();
					String result = restTemplate.getForObject(url, String.class);
					JSONObject jsonObject = JSONObject.fromObject(result);
					LOG.info("RESULT================purchaseShopping" + result);
					JSONObject resultbrand = jsonObject.getJSONObject("result");

					// uri = util.getServiceUrl("user", "error url request!");
					url = "http://user/v1.0/user/query/id";
					// **根据的用户手机号码查询用户的基本信息*/
					LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("id", resultbrand.getString("manageid"));
					// restTemplate = new RestTemplate();
					result = restTemplate.postForObject(url, requestEntity, String.class);
					LOG.info("RESULT================purchaseShopping" + result);
					jsonObject = JSONObject.fromObject(result);
					JSONObject resultObju = jsonObject.getJSONObject("result");
					String phone = null;
					if (resultObju.containsKey("phone")) {
						phone = resultObju.getString("phone");
					}
					/** 计算分润的钱 */
					BigDecimal rebate = order.getRealAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

					/** 存贮分润记录明细 */
					ProfitRecord profitRecord = new ProfitRecord();
					profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
					profitRecord.setAcqAmount(rebate);
					profitRecord.setAcqphone(phone);
					profitRecord.setAcqrate(new BigDecimal("0.0"));
					profitRecord.setAcquserid(Long.parseLong(resultObju.getString("id")));
					profitRecord.setAmount(order.getRealAmount());
					profitRecord.setCreateTime(new Date());
					profitRecord.setOrdercode(ordercode);
					profitRecord.setOriphone(order.getPhone());
					profitRecord.setOrirate(order.getRate());
					profitRecord.setOriuserid(order.getUserid());
					profitRecord.setRemark("产品剩余金额");
					profitRecord.setScale(BigDecimal.ONE);
					profitRecord.setType("3");
					profitRecordBusiness.merge(profitRecord);

					/** 存储 用户的分润记录 */
					// restTemplate = new RestTemplate();
					// uri = util.getServiceUrl("user", "error url request!");
					url = "http://user/v1.0/user/rebate/update";
					/** 根据的渠道标识或去渠道的相关信息 */
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("rebate_amount", rebate.toString());
					requestEntity.add("user_id", resultObju.getString("id"));
					requestEntity.add("order_code", ordercode);
					result = restTemplate.postForObject(url, requestEntity, String.class);
				}
			}
			LOG.info("===============444444444444444444===============发放积分判断");
			if (order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_TOPUP)
					|| order.getType().equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)
					|| CommonConstants.ORDER_TYPE_REPAYMENT.equals(order.getType())) {
				/** 发放积分 */
				sendCoin(ordercode, order.getType(), order.getUserid(), order.getPhone(), order.getBrandid(),
						order.getBrandname(), order.getAmount());
			}
		}
		redisTemplate.delete(key);
		resultmap.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		resultmap.put(CommonConstants.RESP_MESSAGE, "成功");
		return resultmap;
	}

	/** 发放用户的返佣 新逻辑 **/
	private void sendThirdDistributionNew(String ordercode, long userid, String phone, BigDecimal amount,
			Map<String, BigDecimal> map, long brandid, String grade) {
		long oriUserId = userid;
		int i = 1;

		long lowerUserId = userid;
		String lowerPhone = phone;

		BigDecimal remainingAmount = amount;
		// RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		// URI uri = util.getServiceUrl("user", "user url request!");
		String url = "http://user/v1.0/user/query/id";

		/** 根据的用户手机号码查询用户的基本信息 */
		requestEntity.add("id", userid + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================/v1.0/user/query/id:" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		long preUserId = resultObj.getLong("preUserId");
		String preUserPhone = resultObj.getString("preUserPhone");
		String oriGrade = resultObj.getString("grade");

		// restTemplate = new RestTemplate();
		// uri = util.getServiceUrl("user", "error url request!");
		url = "http://user/v1.0/user/brand/query/id?brand_id=" + brandid;
		result = restTemplate.getForObject(url, String.class);

		/** 根据的渠道标识或去渠道的相关信息 */
		jsonObject = JSONObject.fromObject(result);
		resultObj = jsonObject.getJSONObject("result");
		String manageId = resultObj.getString("manageid");
		int rebateCount = resultObj.getInt("rebateCount");
		BigDecimal rate = null;
		BigDecimal rate1 = null;
		BigDecimal rate2 = null;
		BigDecimal rate3 = null;
		/** 根据userid 找到上级， 如果上级的等级大于等于他就发放返佣，然后继续循环方法 */
		while (true) {
			if (i > rebateCount) {
				break;
			}
			if (preUserId != 0) {
				// restTemplate = new RestTemplate();
				// uri = util.getServiceUrl("user", "error url request!");
				url = "http://user/v1.0/user/query/id";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("id", preUserId + "");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
				String preGrade = resultObj.getString("grade");
				preUserPhone = resultObj.getString("phone");
				long xPreUserId = resultObj.getLong("preUserId");
				/** 如果上级没有购买三级分销或者前面的三级分销等级比自己的等级低 */
				if ("0".equals(preGrade) || (i == 1
						? new BigDecimal(preGrade)
								.compareTo(new BigDecimal(oriGrade).subtract(new BigDecimal(grade))) < 0
						: new BigDecimal(preGrade).compareTo(new BigDecimal(oriGrade)) < 0)) {
					preUserId = xPreUserId;
					continue;
				} else {
					if (preUserId == Long.valueOf(manageId).longValue()) {
						break;
					}
					if (i == 1) {
						rate1 = map.get(preGrade);
						rate = rate1;
					}
					if (i == 2) {
						rate2 = map.get(preGrade).subtract(rate1);
						if (rate2.compareTo(BigDecimal.ZERO) <= 0) {
							preUserId = xPreUserId;
							continue;
						}
						rate = rate2;
						rate2 = map.get(preGrade);
					}
					if (i == 3) {
						rate3 = map.get(preGrade).subtract(rate2);
						if (rate3.compareTo(BigDecimal.ZERO) <= 0) {
							preUserId = xPreUserId;
							continue;
						}
						rate = rate3;
					}
					/** 存贮分润记录明细 */
					DistributionRecord profitRecord = new DistributionRecord();
					profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
					profitRecord.setAcqphone(preUserPhone);
					profitRecord.setAcquserid(preUserId);
					profitRecord.setAmount(amount);
					profitRecord.setAcqAmount(rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
					profitRecord.setAcqratio(map.get(preGrade));
					profitRecord.setCreateTime(new Date());
					profitRecord.setOrdercode(ordercode);
					profitRecord.setOriphone(lowerPhone);
					profitRecord.setOriuserid(lowerUserId);
					profitRecord.setRemark("获得下级用户返佣");
					profitRecordBusiness.merge(profitRecord);

					/** 修改用户的分润 */
					// restTemplate = new RestTemplate();
					// uri = util.getServiceUrl("user", "error url request!");
					url = "http://user/v1.0/user/rebate/update";
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("rebate_amount",
							rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
					requestEntity.add("user_id", preUserId + "");
					requestEntity.add("order_code", ordercode);
					requestEntity.add("order_type", "1");
					result = restTemplate.postForObject(url, requestEntity, String.class);
					remainingAmount = remainingAmount
							.subtract(rate.multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
				}
				lowerUserId = preUserId;
				lowerPhone = preUserPhone;
				preUserId = xPreUserId;
				i++;
			} else {
				break;
			}
		}

		// 将剩余的产品金额给贴牌商
		if (remainingAmount.compareTo(BigDecimal.ZERO) > 0) {
			// restTemplate = new RestTemplate();
			// uri = util.getServiceUrl("user", "error url request!");
			url = "http://user/v1.0/user/query/id";
			/** 根据的渠道标识或去渠道的相关信息 */
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("id", manageId);
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================/v1.0/user/query/id:" + result);
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			String managephone = resultObj.getString("phone");

			/** 存贮分润记录明细 */
			DistributionRecord profitRecord = new DistributionRecord();
			profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
			profitRecord.setAcqAmount(remainingAmount);
			profitRecord.setAcqphone(managephone);
			profitRecord.setAcquserid(Long.parseLong(manageId));
			profitRecord.setAcqratio(BigDecimal.ZERO);
			profitRecord.setAmount(amount);
			profitRecord.setCreateTime(new Date());
			profitRecord.setOrdercode(ordercode);
			profitRecord.setOriphone(phone);
			profitRecord.setOriuserid(userid);
			profitRecord.setRemark("产品剩余分润");
			profitRecordBusiness.merge(profitRecord);

			// 增加贴牌商余额
			// restTemplate = new RestTemplate();
			// uri = util.getServiceUrl("user", "error url request!");
			url = "http://user/v1.0/user/rebate/update";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("rebate_amount", remainingAmount.toString());
			requestEntity.add("user_id", manageId);
			requestEntity.add("order_code", ordercode);
			requestEntity.add("order_type", "1");
			result = restTemplate.postForObject(url, requestEntity, String.class);
		}
	}

	/** 发放用户的返佣 **/
	private void sendThirdDistribution(String ordercode, long userid, String phone, BigDecimal amount,
			Map<String, BigDecimal> map, long brandid) {

		long oriuserid = userid;

		int i = 1;

		BigDecimal remainingAmount = amount;

		// RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		// URI uri = util.getServiceUrl("user", "error url request!");
		String url = "http://user/v1.0/user/query/id";

		/** 根据的用户手机号码查询用户的基本信息 */
		requestEntity.add("id", userid + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		long preuserid = resultObj.getLong("preUserId");
		String preuserphone = resultObj.getString("preUserPhone");
		String origrade = resultObj.getString("grade");
		phone = resultObj.getString("phone");

		/** 根据userid 找到上级， 如果上级的费率比他低就发放分润，然后继续循环方法 */
		while (true) {
			if (i > 3) {
				break;
			}

			/** 用户证明有上级用户 */
			if (preuserid != 0) {
				// restTemplate = new RestTemplate();
				// uri = util.getServiceUrl("user", "error url request!");
				url = "http://user/v1.0/user/query/id";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("id", preuserid + "");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
				preuserphone = resultObj.getString("phone");
				String grade = resultObj.getString("grade");
				long xpreuserid = resultObj.getLong("preUserId");
				String xprephone = resultObj.getString("preUserPhone");
				/** 如果上级没有购买三级分销或者前面的三级分销等级比自己的等级低 */
				if (grade.equalsIgnoreCase("0") || new BigDecimal(grade).compareTo(new BigDecimal(origrade)) < 0) {
					preuserphone = xprephone;
					preuserid = xpreuserid;
					continue;
				} else {
					if (map.get(grade) != null) {
						/** 存贮分润记录明细 */
						DistributionRecord profitRecord = new DistributionRecord();
						// profitRecord.setAcqAmount(rebate);
						profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
						profitRecord.setAcqphone(preuserphone);
						profitRecord.setAcquserid(preuserid);
						profitRecord.setAmount(amount);
						profitRecord
								.setAcqAmount(map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
						profitRecord.setAcqratio(map.get(grade));
						profitRecord.setCreateTime(new Date());
						profitRecord.setOrdercode(ordercode);
						profitRecord.setOriphone(phone);
						profitRecord.setOriuserid(oriuserid);
						profitRecord.setRemark("产品分润");
						profitRecordBusiness.merge(profitRecord);

						/** 存储 用户的分润记录 */
						// restTemplate = new RestTemplate();
						// uri = util.getServiceUrl("user", "error url request!");
						url = "http://user/v1.0/user/rebate/update";
						/** 根据的渠道标识或去渠道的相关信息 */
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("rebate_amount",
								map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
						requestEntity.add("user_id", preuserid + "");
						requestEntity.add("order_code", ordercode);
						requestEntity.add("order_type", "1");
						result = restTemplate.postForObject(url, requestEntity, String.class);
						remainingAmount = remainingAmount
								.subtract(map.get(grade).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
				}

				i++;

				preuserphone = xprephone;
				preuserid = xpreuserid;

				/** 当前用户作为下一次循环的初始用户了 */
				// userid = preuserid;

			} else {

				break;
			}
		}

		/** 讲剩余的产品金额给贴牌商 */
		if (remainingAmount.compareTo(BigDecimal.ZERO) > 0) {

			// restTemplate = new RestTemplate();
			// uri = util.getServiceUrl("user", "error url request!");
			url = "http://user/v1.0/user/brand/query/id?brand_id=" + brandid;
			result = restTemplate.getForObject(url, String.class);

			/** 根据的渠道标识或去渠道的相关信息 */
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			String manageid = resultObj.getString("manageid");

			/** 根据manageid获取用户 */
			// uri = util.getServiceUrl("user", "error url request!");
			url = "http://user/v1.0/user/query/id";
			/** 根据的渠道标识或去渠道的相关信息 */
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("id", manageid);
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			String managephone = resultObj.getString("phone");

			/** 存贮分润记录明细 */
			DistributionRecord profitRecord = new DistributionRecord();
			profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
			profitRecord.setAcqAmount(remainingAmount);
			profitRecord.setAcqratio(BigDecimal.ZERO);
			profitRecord.setAcqphone(managephone);
			profitRecord.setAcquserid(Long.parseLong(manageid));
			profitRecord.setAmount(amount);
			profitRecord.setCreateTime(new Date());
			profitRecord.setOrdercode(ordercode);
			profitRecord.setOriphone(phone);
			profitRecord.setOriuserid(userid);
			profitRecord.setRemark("产品剩余分润");
			profitRecordBusiness.merge(profitRecord);

			/** 存储 用户的分润记录 */
			// restTemplate = new RestTemplate();
			// uri = util.getServiceUrl("user", "error url request!");
			url = "http://user/v1.0/user/rebate/update";
			/** 根据的渠道标识或去渠道的相关信息 */
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("rebate_amount", remainingAmount.toString());
			requestEntity.add("user_id", manageid);
			requestEntity.add("order_code", ordercode);
			requestEntity.add("order_type", "1");
			result = restTemplate.postForObject(url, requestEntity, String.class);
		}
	}

	/** 发放用户的积分 */
	private void sendCoin(String ordercode, String type, long userid, String phone, long brandid, String brandname,
			BigDecimal amount) {

		// RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		// URI uri = util.getServiceUrl("user", "error url request!");
		String url = "http://user/v1.0/user/brandcoin/query";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("brand_id", brandid + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		String ratio = resultObj.getString("ratio");

		BigDecimal coinBd = amount.divide(new BigDecimal(ratio), RoundingMode.DOWN);

		CoinRecord coinRecord = new CoinRecord();
		coinRecord.setBrand_id(brandid);
		coinRecord.setCoin(coinBd.intValue());
		coinRecord.setCreateTime(new Date());
		coinRecord.setOrdercode(ordercode);
		coinRecord.setBrand_name(brandname);
		if (type.equalsIgnoreCase(CommonConstants.ORDER_TYPE_PAY)) {
			coinRecord.setRemark("消费返积分");
		} else {
			coinRecord.setRemark("充值返积分");
		}
		coinRecord.setType(CommonConstants.COIN_TYPE_ADD);
		coinRecord.setUserid(userid);
		coinRecord.setUserphone(phone);
		coinRecordBusiness.mergeCoinRecord(coinRecord);

		/** 存储 用户的积分记录 */
		// restTemplate = new RestTemplate();
		// uri = util.getServiceUrl("user", "error url request!");
		url = "http://user/v1.0/user/coin/update/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid + "");
		requestEntity.add("coin", coinBd.intValue() + "");
		requestEntity.add("order_code", ordercode);
		result = restTemplate.postForObject(url, requestEntity, String.class);
	}

	private void rebate2(String ordercode, long userid, long channelId, BigDecimal amount, BigDecimal currate,
			long brandid) {
		boolean isCancel = false;
		boolean isequalRebateRate = false;
		String equalRebateRate = "";

		RestTemplate restTemplate = new RestTemplate();
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/query/id";

		/** 根据的用户手机号码查询用户的基本信息 */
		requestEntity.add("id", userid + "");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		String grade = resultObj.getString("grade");
		Integer equalGrade = Integer.valueOf("0".equals(grade) ? "1" : grade);
		/** 根据userid 找到上级， 如果上级的费率比他低就发放分润，然后继续循环方法 */
		while (true) {

			if (isCancel) {
				break;
			}

			restTemplate = new RestTemplate();
			requestEntity = new LinkedMultiValueMap<String, String>();
			restTemplate = new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/query/id";

			/** 根据的用户手机号码查询用户的基本信息 */
			requestEntity.add("id", userid + "");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
			String oriphone = resultObj.getString("phone");
			long preuserid = resultObj.getLong("preUserId");
			grade = resultObj.getString("grade");

			String preuserphone = resultObj.getString("preUserPhone");

			/** 用户证明有上级用户 */
			if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

				restTemplate = new RestTemplate();
				uri = util.getServiceUrl("user", "error url request!");
				url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

				/** 根据的渠道标识或去渠道的相关信息 */
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("channel_id", channelId + "");
				requestEntity.add("user_id", preuserid + "");

				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);

				if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
					LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
					// throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
					userid = preuserid;
					continue;
				}

				resultObj = jsonObject.getJSONObject("result");
				String rate = resultObj.getString("rate");

				/** 证明上级的费率小于当前 */
				if (new BigDecimal(rate).compareTo(currate) < 0) {

					/** 计算分润的钱 */
					BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount).setScale(2,
							BigDecimal.ROUND_HALF_UP);
					if (rebate.toString().equals("0.00")) {
						/** 当前用户作为下一次循环的初始用户了 */
						userid = preuserid;
						currate = new BigDecimal(rate);
						continue;
					}
					/** 存贮分润记录明细 */
					ProfitRecord profitRecord = new ProfitRecord();
					profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
					;
					profitRecord.setAcqAmount(rebate);
					profitRecord.setAcqphone(preuserphone);
					profitRecord.setAcqrate(new BigDecimal(rate));
					profitRecord.setAcquserid(preuserid);
					profitRecord.setAmount(amount);
					profitRecord.setCreateTime(new Date());
					profitRecord.setOrdercode(ordercode);
					profitRecord.setOriphone(oriphone);
					profitRecord.setOrirate(currate);
					profitRecord.setOriuserid(userid);
					profitRecord.setRemark("差额费率分润");
					profitRecord.setScale(BigDecimal.ONE);
					profitRecord.setType("0");
					profitRecordBusiness.merge(profitRecord);

					/** 存储 用户的分润记录 */
					restTemplate = new RestTemplate();
					uri = util.getServiceUrl("user", "error url request!");
					url = uri.toString() + "/v1.0/user/rebate/update";
					/** 根据的渠道标识或去渠道的相关信息 */
					requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("rebate_amount", rebate.toString());
					requestEntity.add("user_id", preuserid + "");
					requestEntity.add("order_code", ordercode);
					result = restTemplate.postForObject(url, requestEntity, String.class);

					/** 当前用户作为下一次循环的初始用户了 */
					userid = preuserid;
					currate = new BigDecimal(rate);
					continue;

				} else {

					if (!isequalRebateRate) {
						/** 根据品牌id获取同级的分润比率 */
						restTemplate = new RestTemplate();
						uri = util.getServiceUrl("user", "error url request!");
						url = uri.toString() + "/v1.0/user/brand/query/id?brand_id=" + brandid;
						result = restTemplate.getForObject(url, String.class);
						jsonObject = JSONObject.fromObject(result);
						resultObj = jsonObject.getJSONObject("result");
						equalRebateRate = resultObj.getString("equalRebateRate");

						isequalRebateRate = true;
					}
					/** 寻找比自己费率低的 */

					while (true) {

						/** 先发放同级分润 */
						if (equalRebateRate != null && !equalRebateRate.equalsIgnoreCase("")
								&& !equalRebateRate.equalsIgnoreCase("null")) {

							if (new BigDecimal(equalRebateRate).compareTo(BigDecimal.ZERO) > 0) {

								restTemplate = new RestTemplate();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/query/id";
								requestEntity = new LinkedMultiValueMap<String, String>();
								requestEntity.add("id", preuserid + "");
								result = restTemplate.postForObject(url, requestEntity, String.class);
								LOG.info("RESULT================" + result);
								jsonObject = JSONObject.fromObject(result);
								resultObj = jsonObject.getJSONObject("result");
								String pregrade = resultObj.getString("grade");
								if (equalGrade.equals(Integer.valueOf(pregrade))
										&& Integer.parseInt(pregrade) == Integer.parseInt(grade)) {
									equalGrade = equalGrade + 1;

									uri = util.getServiceUrl("user", "error url request!");
									url = uri.toString() + "/v1.0/user/rebate/query/sumrebatepremonth";
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("user_id", String.valueOf(userid));
									restTemplate = new RestTemplate();
									result = restTemplate.postForObject(url, requestEntity, String.class);
									LOG.info("RESULT================purchaseShopping" + result);
									jsonObject = JSONObject.fromObject(result);
									LOG.info("jsonObject================" + jsonObject);
									BigDecimal currentrebate = new BigDecimal("0");
									if (jsonObject.containsKey("result")) {
										JSONObject UserAccount = jsonObject.getJSONObject("result");
										currentrebate = new BigDecimal(UserAccount.getString("monthRebate"));
									}
									uri = util.getServiceUrl("user", "error url request!");
									url = uri.toString() + "/v1.0/user/rebate/query/sumrebatepremonth";
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("user_id", String.valueOf(preuserid));
									restTemplate = new RestTemplate();
									result = restTemplate.postForObject(url, requestEntity, String.class);
									LOG.info("RESULT================purchaseShopping" + result);
									jsonObject = JSONObject.fromObject(result);
									LOG.info("jsonObject================" + jsonObject);
									BigDecimal prerebate = new BigDecimal("0");
									if (jsonObject.containsKey("result")) {
										JSONObject UserAccount = jsonObject.getJSONObject("result");
										prerebate = new BigDecimal(UserAccount.getString("monthRebate"));
									}
									/** 计算分润的钱 */
									BigDecimal rebate = new BigDecimal("0");
									if (currentrebate.compareTo(prerebate) < 0) {
										rebate = new BigDecimal(equalRebateRate).multiply(currentrebate).setScale(2,
												BigDecimal.ROUND_HALF_UP);
									} else {
										rebate = new BigDecimal(equalRebateRate).multiply(prerebate).setScale(2,
												BigDecimal.ROUND_HALF_UP);
									}
									LOG.info("===============用户ID" + preuserid + "," + "获得分润:" + rebate.toString()
											+ "===============");
									if (rebate.toString().equals("0.00")) {
										userid = preuserid;
										currate = new BigDecimal(rate);
										break;
									}
									/** 存贮分润记录明细 */
									ProfitRecord profitRecord = new ProfitRecord();
									profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
									profitRecord.setAcqAmount(rebate);
									profitRecord.setAcqphone(preuserphone);
									profitRecord.setAcqrate(new BigDecimal(rate));
									profitRecord.setAcquserid(preuserid);
									profitRecord.setAmount(amount);
									profitRecord.setCreateTime(new Date());
									profitRecord.setOrdercode(ordercode);
									profitRecord.setOriphone(oriphone);
									profitRecord.setOrirate(currate);
									profitRecord.setOriuserid(userid);
									profitRecord.setRemark("平级分润");
									profitRecord.setScale(BigDecimal.ONE);
									profitRecord.setType("3");
									profitRecordBusiness.merge(profitRecord);

									/** 存储 用户的分润记录 */
									restTemplate = new RestTemplate();
									uri = util.getServiceUrl("user", "error url request!");
									url = uri.toString() + "/v1.0/user/rebate/update";
									/** 根据的渠道标识或去渠道的相关信息 */
									requestEntity = new LinkedMultiValueMap<String, String>();
									requestEntity.add("rebate_amount", rebate.toString());
									requestEntity.add("user_id", preuserid + "");
									requestEntity.add("order_code", ordercode);
									result = restTemplate.postForObject(url, requestEntity, String.class);

									LOG.info("平级分润================================受益人:" + preuserid + ",等级:" + pregrade
											+ ",平级等级:" + equalGrade);

								}
							}
						}
						restTemplate = new RestTemplate();
						requestEntity = new LinkedMultiValueMap<String, String>();
						restTemplate = new RestTemplate();
						uri = util.getServiceUrl("user", "error url request!");
						url = uri.toString() + "/v1.0/user/query/id";

						/** 根据的用户手机号码查询用户的基本信息 */
						requestEntity.add("id", preuserid + "");
						result = restTemplate.postForObject(url, requestEntity, String.class);
						LOG.info("RESULT================" + result);
						jsonObject = JSONObject.fromObject(result);
						resultObj = jsonObject.getJSONObject("result");
						preuserid = resultObj.getLong("preUserId");
						grade = resultObj.getString("grade");
						preuserphone = resultObj.getString("preUserPhone");

						/** 用户证明有上级用户 */
						if (preuserid != 0 && preuserphone != null && !preuserphone.equalsIgnoreCase("")) {

							restTemplate = new RestTemplate();
							uri = util.getServiceUrl("user", "error url request!");
							url = uri.toString() + "/v1.0/user/channel/rate/query/userid";

							/** 根据的渠道标识或去渠道的相关信息 */
							requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("channel_id", channelId + "");
							requestEntity.add("user_id", preuserid + "");

							result = restTemplate.postForObject(url, requestEntity, String.class);
							LOG.info("RESULT================" + result);
							jsonObject = JSONObject.fromObject(result);

							if (!CommonConstants.SUCCESS.equals(jsonObject.getString(CommonConstants.RESP_CODE))) {
								LOG.error("亲.无渠道费率,请配置渠道费率哦!======userId:" + preuserid + "channelId:" + channelId);
								// throw new RuntimeException("亲.无渠道费率,请配置渠道费率哦!");
								userid = preuserid;
								continue;
							}

							resultObj = jsonObject.getJSONObject("result");
							rate = resultObj.getString("rate");

							/** 证明上级的费率小于当前 */
							if (new BigDecimal(rate).compareTo(currate) < 0) {

								/** 计算分润的钱 */
								BigDecimal rebate = (currate.subtract(new BigDecimal(rate))).multiply(amount)
										.setScale(2, BigDecimal.ROUND_HALF_UP);
								if (rebate.toString().equals("0.00")) {
									/** 当前用户作为下一次循环的初始用户了 */
									userid = preuserid;
									currate = new BigDecimal(rate);
									break;
								}
								/** 存贮分润记录明细 */
								ProfitRecord profitRecord = new ProfitRecord();
								profitRecord.setId(Long.parseLong(RandomUtils.generateNumString(8)));
								;
								profitRecord.setAcqAmount(rebate);
								profitRecord.setAcqphone(preuserphone);
								profitRecord.setAcqrate(new BigDecimal(rate));
								profitRecord.setAcquserid(preuserid);
								profitRecord.setAmount(amount);
								profitRecord.setCreateTime(new Date());
								profitRecord.setOrdercode(ordercode);
								profitRecord.setOriphone(oriphone);
								profitRecord.setOrirate(currate);
								profitRecord.setOriuserid(userid);
								profitRecord.setRemark("差额费率分润");
								profitRecord.setScale(BigDecimal.ONE);
								profitRecord.setType("0");
								profitRecordBusiness.merge(profitRecord);

								/** 存储 用户的分润记录 */
								restTemplate = new RestTemplate();
								uri = util.getServiceUrl("user", "error url request!");
								url = uri.toString() + "/v1.0/user/rebate/update";
								/** 根据的渠道标识或去渠道的相关信息 */
								requestEntity = new LinkedMultiValueMap<String, String>();
								requestEntity.add("rebate_amount", rebate.toString());
								requestEntity.add("user_id", preuserid + "");
								requestEntity.add("order_code", ordercode);
								result = restTemplate.postForObject(url, requestEntity, String.class);

								/** 当前用户作为下一次循环的初始用户了 */
								userid = preuserid;
								currate = new BigDecimal(rate);
								break;
							}

						} else {
							isCancel = true;
							break;

						}
					}

				}

			} else {

				break;
			}
		}

	}

	/** 循环处理用户的分润 */
	/**
	 * 分润的发放逻辑如下，如果刷卡用户的上级登记比自己高，那上级那自己的分润，如果上级的等级美欧自己的高，那么继续寻找上面一个比自己低的拿分润
	 * 拿到分润的用户作为下一次循环的起点， 直接没有上级为止
	 */
	private void rebate(String ordercode, long userid, long channelId, BigDecimal amount, BigDecimal currate,
			long brandid) {
		boolean isequalRebateRate = false;
		String equalRebateRate = "0";

		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", userid + "");
		requestEntity.add("channelId", channelId + "");
		Map<String, Object> restTemplateDoPost = restTemplateUtil.restTemplateDoPost("user","/v1.0/user/realtion/query/preuser", requestEntity);
		if (CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))) {
			JSONArray jsonArray = ((JSONObject) restTemplateDoPost.get(CommonConstants.RESULT)).getJSONArray(CommonConstants.RESULT);
			List<UserRealtion> userRealtions = new ArrayList<UserRealtion>();
			BigDecimal totalRebate = BigDecimal.ZERO;
			BigDecimal minRate = BigDecimal.ZERO;
			if (jsonArray.size() > 0) {
				int rebateCount = 0;
				UserRealtion preUserRealtion = null;
				for (int i = 0; i < jsonArray.size(); i++) {
					Object jsonObject = jsonArray.get(i);
					UserRealtion userRealtion = new UserRealtion();
					try {
						BeanUtils.copyProperties(userRealtion, jsonObject);
					} catch (IllegalAccessException | InvocationTargetException e) {
						e.printStackTrace();
						LOG.error(ExceptionUtil.errInfo(e));
						continue;
					}
					if (i == 0) {
						minRate = userRealtion.getRate();
					} else if (minRate.compareTo(userRealtion.getRate()) > 0) {
						minRate = userRealtion.getRate();
					}
					userRealtions.add(userRealtion);
					LOG.info("用户上级为=================" + userRealtion);
				}

				// UserRealtion brandUserRealtion = userRealtions.get(userRealtions.size()-1);
				totalRebate = currate.subtract(minRate).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_DOWN);
				LOG.info("订单====" + ordercode + "====总分润为====:" + totalRebate);

				Map<String, Object> restTemplateDoGet = restTemplateUtil.restTemplateDoGet("user","/v1.0/user/brand/query/id?brand_id=" + brandid);
				if (CommonConstants.SUCCESS.equals(restTemplateDoGet.get(CommonConstants.RESP_CODE))) {
					JSONObject resultJSON = (JSONObject) restTemplateDoGet.get(CommonConstants.RESULT);
					equalRebateRate = resultJSON.getString("equalRebateRate");
				}
				
				for (UserRealtion userRealtion : userRealtions) {
					if (BigDecimal.ZERO.compareTo(totalRebate) >= 0) {
						break;
					}
					if (userRealtion.getLevel().intValue() == 1) {
						if (userRealtion.getFirstUserGrade().intValue() == userRealtion.getPreUserGrade().intValue()) {
							BigDecimal subtract = userRealtion.getRate().subtract(new BigDecimal(equalRebateRate));
							if (subtract.compareTo(userRealtion.getRate()) < 0) {
								userRealtion.setRate(subtract);
							}
						}
					}
					BigDecimal preRate = userRealtion.getRate();
					if (currate.compareTo(preRate) > 0) {
						BigDecimal rebate = currate.subtract(preRate).multiply(amount).setScale(2,BigDecimal.ROUND_HALF_DOWN);
						if (BigDecimal.ZERO.compareTo(rebate) >= 0) {
							continue;
						}
						String firstPhone = "";
						Long firstUserId = null;

						if (rebateCount == 0) {
							firstPhone = userRealtion.getFirstUserPhone();
							firstUserId = userRealtion.getFirstUserId();
						} else {
							firstPhone = preUserRealtion.getPreUserPhone();
							firstUserId = preUserRealtion.getPreUserId();
						}

						totalRebate = totalRebate.subtract(rebate);
						if (BigDecimal.ZERO.compareTo(totalRebate) > 0) {
							rebate = totalRebate.add(rebate);
						}

						this.updateRebate(rebate + "", userRealtion.getPreUserId() + "", ordercode, null);
						profitRecordBusiness.createNewProfitRecord(rebate, userRealtion.getPreUserPhone(),
								userRealtion.getRate(), userRealtion.getPreUserId(), amount, ordercode, firstUserId,
								firstPhone, currate, "0", BigDecimal.ONE, "差额费率分润");
						currate = userRealtion.getRate();
						preUserRealtion = userRealtion;
						rebateCount += 1;
					}
				}
			}

			/*if (jsonArray.size() > 0) {
				String manageId = "";
				if (!isequalRebateRate) {
					*//** 根据品牌id获取同级的分润比率 *//*
					Map<String, Object> restTemplateDoGet = restTemplateUtil.restTemplateDoGet("user","/v1.0/user/brand/query/id?brand_id=" + brandid);
					if (CommonConstants.SUCCESS.equals(restTemplateDoGet.get(CommonConstants.RESP_CODE))) {
						JSONObject resultJSON = (JSONObject) restTemplateDoGet.get(CommonConstants.RESULT);
						equalRebateRate = resultJSON.getString("equalRebateRate");
						manageId = resultJSON.getString("manageid");
						isequalRebateRate = true;
					}
				}

				if (equalRebateRate != null && !"".equals(equalRebateRate) && !"null".equals(equalRebateRate)&& BigDecimal.ZERO.compareTo(new BigDecimal(equalRebateRate)) < 0) {
					Integer equalGrade = null;
					int maxGrade = 0;
					int beganGrade = 1;
					for (int i = 0; i < userRealtions.size(); i++) {
						UserRealtion userRealtion = userRealtions.get(i);
						Integer preUserGrade = userRealtion.getPreUserGrade();
						if (i == 0) {
							maxGrade = preUserGrade.intValue();
							if (userRealtion.getFirstUserGrade().intValue() != 0) {
								beganGrade = userRealtion.getFirstUserGrade().intValue();
							}
						}

						if (maxGrade < preUserGrade.intValue()) {
							maxGrade = preUserGrade.intValue();
						}
					}

					equalGrade = beganGrade;

					for (int i = beganGrade; i <= maxGrade; i++) {
						int equalCount = 0;
						for (int j = 0; j < userRealtions.size() - 1; j++) {
							UserRealtion userRealtion2 = userRealtions.get(j);

							if (userRealtion2.getPreUserGrade().compareTo(equalGrade) == 0) {
								if (i == beganGrade) {
									if (equalCount == 0) {
										BigDecimal rebate = new BigDecimal(equalRebateRate).multiply(amount).setScale(2,
												BigDecimal.ROUND_HALF_DOWN);
										this.updateRebate(rebate + "", userRealtion2.getPreUserId() + "", ordercode,
												manageId);
										profitRecordBusiness.createNewProfitRecord(rebate,
												userRealtion2.getPreUserPhone(), userRealtion2.getRate(),
												userRealtion2.getPreUserId(), amount, ordercode,
												userRealtion2.getFirstUserId(), userRealtion2.getFirstUserPhone(),
												currate, "3", BigDecimal.ONE, "平级分润");
										equalGrade += 1;
									} else if (equalCount % 2 == 0) {
										BigDecimal rebate = new BigDecimal(equalRebateRate).multiply(amount).setScale(2,
												BigDecimal.ROUND_HALF_DOWN);
										this.updateRebate(rebate + "", userRealtion2.getPreUserId() + "", ordercode,
												manageId);
										profitRecordBusiness.createNewProfitRecord(rebate,
												userRealtion2.getPreUserPhone(), userRealtion2.getRate(),
												userRealtion2.getPreUserId(), amount, ordercode,
												userRealtion2.getFirstUserId(), userRealtion2.getFirstUserPhone(),
												currate, "3", BigDecimal.ONE, "平级分润");

										equalGrade += 1;
									}
								} else {
									if (equalCount % 2 != 0) {
										BigDecimal rebate = new BigDecimal(equalRebateRate).multiply(amount).setScale(2,
												BigDecimal.ROUND_HALF_DOWN);
										this.updateRebate(rebate + "", userRealtion2.getPreUserId() + "", ordercode,
												manageId);
										profitRecordBusiness.createNewProfitRecord(rebate,
												userRealtion2.getPreUserPhone(), userRealtion2.getRate(),
												userRealtion2.getPreUserId(), amount, ordercode,
												userRealtion2.getFirstUserId(), userRealtion2.getFirstUserPhone(),
												currate, "3", BigDecimal.ONE, "平级分润");

										equalGrade += 1;
									}
								}
								equalCount += 1;
							}
						}
						if (i == equalGrade.intValue()) {
							equalGrade += 1;
						}
					}
				}
			}*/
		}
	}

	private void updateRebate(String rebateAmount, String userId, String orderCode, String manageId) {
		MultiValueMap<String, String> requestEntity = null;
		if (null == manageId) {
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("rebate_amount", rebateAmount);
			requestEntity.add("user_id", userId);
			requestEntity.add("order_code", orderCode);
			restTemplateUtil.restTemplateDoPost("user", "/v1.0/user/rebate/update", requestEntity);
		} else {
			if (!"".equals(manageId) && null != manageId) {
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("user_id", manageId);
				Map<String, Object> restTemplateDoPost = restTemplateUtil.restTemplateDoPost("user",
						"/v1.0/user/account/query/userId", requestEntity);
				if (CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))) {
					JSONObject userAccountJSON = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
					String balance = userAccountJSON.getString("balance");
					if (new BigDecimal(rebateAmount).compareTo(new BigDecimal(balance)) <= 0) {
						// 增加用户分润
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("rebate_amount", rebateAmount);
						requestEntity.add("user_id", userId);
						requestEntity.add("order_code", orderCode);
						restTemplateUtil.restTemplateDoPost("user", "/v1.0/user/rebate/update", requestEntity);
						// 减少贴牌商余额
						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("amount", rebateAmount);
						requestEntity.add("user_id", manageId);
						requestEntity.add("addorsub", "1");
						requestEntity.add("order_code", orderCode);
						restTemplateUtil.restTemplateDoPost("user", "/v1.0/user/account/update", requestEntity);

					}
				}
			}
		}
	}

	public int getIntervalDays(Date fDate, Date oDate) {

		/*
		 * if (null == fDate || null == oDate) {
		 * 
		 * return -1;
		 * 
		 * }
		 * 
		 * long intervalMilli = oDate.getTime() - fDate.getTime();
		 * 
		 * return (int) (intervalMilli / (24 * 60 * 60 * 1000));
		 */

		Calendar aCalendar = Calendar.getInstance();

		aCalendar.setTime(fDate);

		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

		aCalendar.setTime(oDate);
		// aCalendar.add(Calendar.HOUR_OF_DAY, -17);
		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

		return day2 - day1;

	}

	/**
	 * 查询提现总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/userid")
	public @ResponseBody Object findAllChannelByuserid(HttpServletRequest request,
			@RequestParam(value = "user_id") long userid, @RequestParam(value = "type") String type,
			@RequestParam(value = "status", defaultValue = "1", required = false) String status,
			@RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {
		String[] str1 = type.split(",");
		String[] str2 = status.split(",");
		BigDecimal simrealAmount = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT,
				simrealAmount == null ? "0.00" : simrealAmount.setScale(2, BigDecimal.ROUND_DOWN));
		return map;
	}

	// 批量查询指定type的总金额
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/byuserids")
	public @ResponseBody Object findAllChannelSumByUserIds(HttpServletRequest request,
			@RequestParam(value = "userIds") String[] suserIds, @RequestParam(value = "type") String type,
			@RequestParam(value = "status", required = false, defaultValue = "1") String status,
			@RequestParam(value = "autoClearing", required = false, defaultValue = "0") String autoClearing) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<Object, Object> sumMap = new HashMap<Object, Object>();
		long[] userIds = new long[suserIds.length];
		if (suserIds != null && suserIds.length > 0) {
			for (int i = 0; i < suserIds.length; i++) {
				userIds[i] = Long.valueOf(suserIds[i]);
			}
			List<Object[]> models = paymentOrderBusiness.findSumByUserIds(userIds, type, status, autoClearing);
			for (int i = 0; i < models.size(); i++) {
				sumMap.put(models.get(i)[0], models.get(i)[1]);
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, sumMap);
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败");
		}
		return map;
	}

	/**
	 * 查询提现总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/userid")
	public @ResponseBody Object findAllChannelByuseridsum(HttpServletRequest request,
			@RequestParam(value = "user_id") long userid,
			@RequestParam(value = "type", defaultValue = "", required = false) String type,
			@RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
			@RequestParam(value = "end_time", required = false) String startTime,
			@RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {

		Date startTimeDate = null;
		if (startTime != null && !startTime.equalsIgnoreCase("")) {
			startTimeDate = DateUtil.getDateFromStr(startTime);
		} else {
			startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			startTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null;
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(startTimeDate);
		calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
		endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
		/** 总入金 **/
		BigDecimal RechargeSum = null;
		/** 总提现 **/
		BigDecimal withdrawSum = null;
		/** 交易笔数 **/
		int transactionCount = 0;
		{
			type = "0";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			RechargeSum = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing, startTimeDate,
					endTimeDate);
		}
		{
			type = "2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			withdrawSum = paymentOrderBusiness.findsumPaymentOrder(userid, str1, str2, autoClearing, startTimeDate,
					endTimeDate);
		}
		{
			type = "0,2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			transactionCount = paymentOrderBusiness.findsumPaymentOrderCount(userid, str1, str2, autoClearing,
					startTimeDate, endTimeDate);
		}

		Map sumall = new HashMap();
		sumall.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
		sumall.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
		sumall.put("transactionCount", transactionCount);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, sumall);
		return map;
	}

	/**
	 * 查询提现总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/sum/userid/query")
	public @ResponseBody Object findAllChannelByuseridquerysum(HttpServletRequest request,
			@RequestParam(value = "user_id") long userid,
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
			@RequestParam(value = "auto_clearing", defaultValue = "0", required = false) String autoClearing) {

		int transactionCount = 0;
		String[] str1 = type.split(",");
		String[] str2 = status.split(",");
		Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
		Date endTimeDate = new Date();
		transactionCount = paymentOrderBusiness.findsumPaymentOrderCount(userid, str1, str2, autoClearing,
				startTimeDate, endTimeDate);

		// Map sumall = new HashMap();
		// sumall.put("transactionCount",transactionCount);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, transactionCount);
		return map;
	}

	/*
	 * public static void main(String[] args) throws Exception{
	 * 
	 * 
	 * String date1 = "2016-07-09 11:23:23"; String date2 = "2016-07-10 17:23:23";
	 * 
	 * 
	 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 * 
	 * Date newDate1 = sdf.parse(date1); Date newDate2 = sdf.parse(date2);
	 * 
	 * Calendar aCalendar = Calendar.getInstance();
	 * 
	 * aCalendar.setTime(newDate1);
	 * 
	 * int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
	 * 
	 * aCalendar.setTime(newDate2); aCalendar.add(Calendar.HOUR_OF_DAY, -17); int
	 * day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
	 * 
	 * System.out.println(day2 - day1);
	 * 
	 * 
	 * 
	 * }
	 */

	/**
	 * 查询提现brand总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/brand")
	public @ResponseBody Object findAllChannelByBrandsum(HttpServletRequest request,
			@RequestParam(value = "brand_id") long brandId,
			@RequestParam(value = "type", defaultValue = "1", required = false) String type,
			@RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
			@RequestParam(value = "end_time", required = false) String startTime,
			@RequestParam(value = "auto_clearing", defaultValue = "0,1", required = false) String autoClearing) {
		Map daysum = new HashMap();
		Map monthsum = new HashMap();
		Map allsum = new HashMap();
		Map body = new HashMap();
		{
			Date startTimeDate = null;
			if (startTime != null && !startTime.equalsIgnoreCase("")) {
				startTimeDate = DateUtil.getDateFromStr(startTime);
			} else {
				startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}
			Date endTimeDate = null;
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
			body.put("daysum", getBrandsum(brandId, startTimeDate, endTimeDate, type, status, autoClearing));
		}
		{
			Date startTimeDate = null;
			if (startTime != null && !startTime.equalsIgnoreCase("")) {
				startTime = new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
				startTimeDate = getYYMMDateFromStr(startTime);
			} else {
				startTime = new SimpleDateFormat("yyyy-MM").format(new Date());
				startTimeDate = getYYMMDateFromStr(startTime);
			}
			Date endTimeDate = null;
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.MONTH, 1);// 把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
			body.put("monthsum", getBrandsum(brandId, startTimeDate, endTimeDate, type, status, autoClearing));
		}

		{
			Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
			Date endTimeDate = new Date();
			body.put("allsum", getBrandsum(brandId, startTimeDate, endTimeDate, type, "1", autoClearing));
		}
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, body);
		return map;
	}

	/**
	 * 获取红包或其他类型今日交易笔数
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/desccode/query/userid")
	public @ResponseBody Object findAllChannelByDescCode(HttpServletRequest request,
			@RequestParam(value = "user_id") long userid,
			@RequestParam(value = "type", defaultValue = "0", required = false) String type,
			@RequestParam(value = "status", defaultValue = "1", required = false) String status,
			@RequestParam(value = "desc_code", defaultValue = "RedPayment", required = false) String desccode) {
		String[] str1 = type.split(",");
		String[] str2 = status.split(",");
		Date startTimeDate = null;
		String startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		startTimeDate = DateUtil.getDateFromStr(startTime);
		Date endTimeDate = null;
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(startTimeDate);
		calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
		endTimeDate = calendar.getTime(); //
		List<PaymentOrder> simrealAmount = paymentOrderBusiness.findsumPaymentOrderByDescCode(userid, str1, str2,
				desccode, startTimeDate, endTimeDate);
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		if (simrealAmount != null && simrealAmount.size() > 0) {
			map.put(CommonConstants.RESULT, simrealAmount);
		}

		return map;
	}

	/**
	 * 查询提现Platform总金额
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/query/sum/platform")
	public @ResponseBody Object findAllChannelByPlatformsum(HttpServletRequest request,
			@RequestParam(value = "type", defaultValue = "", required = false) String type,
			@RequestParam(value = "status", defaultValue = "1,4", required = false) String status,
			@RequestParam(value = "end_time", required = false) String startTime,
			@RequestParam(value = "auto_clearing", defaultValue = "0,1", required = false) String autoClearing) {
		Map daysum = new HashMap();
		Map monthsum = new HashMap();
		Map allsum = new HashMap();
		Map body = new HashMap();
		{
			Date startTimeDate = null;
			if (startTime != null && !startTime.equalsIgnoreCase("")) {
				startTimeDate = DateUtil.getDateFromStr(startTime);
			} else {
				startTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}
			Date endTimeDate = null;
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
			body.put("daysum", getPlatformsum(startTimeDate, endTimeDate, type, status, autoClearing));
		}
		{
			Date startTimeDate = null;
			if (startTime != null && !startTime.equalsIgnoreCase("")) {
				startTime = new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
				startTimeDate = getYYMMDateFromStr(startTime);
			} else {
				startTime = new SimpleDateFormat("yyyy-MM").format(new Date());
				startTimeDate = getYYMMDateFromStr(startTime);
			}
			Date endTimeDate = null;
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.MONTH, 1);// 把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果

			body.put("monthsum", getPlatformsum(startTimeDate, endTimeDate, type, status, autoClearing));
		}

		{
			Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
			Date endTimeDate = new Date();
			body.put("allsum", getPlatformsum(startTimeDate, endTimeDate, type, "1", autoClearing));
		}
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, body);
		return map;
	}

	// 查询用公众号支付商铺扫码的订单
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/queryPaymentOrder")
	public @ResponseBody Object findPaymentOrder(HttpServletRequest request,
			@RequestParam(value = "brand_id", defaultValue = "", required = false) String brandid,
			@RequestParam(value = "user_id", defaultValue = "", required = false) String userid,
			@RequestParam(value = "order_status", defaultValue = "0,1,2,3,4", required = false) String status,
			@RequestParam(value = "order_code", defaultValue = "", required = false) String ordercode,
			@RequestParam(value = "third_order_code", defaultValue = "", required = false) String thirdOrdercode,
			@RequestParam(value = "channel_tag", defaultValue = "3", required = false) String channel_no,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

		String[] statu = status.split(",");
		String[] channel = channel_no.split("");

		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

		Page<PaymentOrder> querypaymentOrder = null;

		if (channel_no != null && !channel_no.equals("")) {
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/channel/channelno";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("channel_no", channel_no);

			RestTemplate restTemplate = new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("result========" + result);
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (jsonObject.containsKey("result") && jsonObject.getString("result").length() > 0) {
				channel = jsonObject.getString("result").split(",");
			}

			querypaymentOrder = paymentOrderBusiness.queryPaymentOrder(userid, brandid, ordercode, statu,
					thirdOrdercode, channel, pageable);
		}

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, querypaymentOrder);

		return map;
	}

	private Map getPlatformsum(Date startTimeDate, Date endTimeDate, String type, String status, String autoClearing) {
		Map Platformsum = new HashMap();
		/** 总入金 **/
		BigDecimal RechargeSum = null;
		/** 总购买 **/
		BigDecimal buyGoodsSum = null;
		/** 总提现 **/
		BigDecimal withdrawSum = null;
		/** 总交易笔数 **/
		int transactionCount = 0;
		// 提现笔数
		int withdrawCount = 0;
		// 充值笔数
		int rechargeCount = 0;
		// 购买商品笔数
		int buyGoodsCount = 0;

		// 购买商品的金额
		{
			type = "1";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			buyGoodsSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 充值的金额
		{
			type = "0";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			RechargeSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 提现的金额
		{
			type = "2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			withdrawSum = paymentOrderBusiness.findsumPaymentOrderPlatform(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 总交易笔数
		{
			type = "0,1,2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			transactionCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 充值的交易笔数
		{
			type = "0";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			rechargeCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 购买商品的交易笔数
		{
			type = "1";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			buyGoodsCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 提现的交易笔数
		{
			type = "2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			withdrawCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 充值的金额
		Platformsum.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
		// 购买商品的金额
		Platformsum.put("buyGoodsSum", buyGoodsSum == null ? "0.00" : buyGoodsSum.setScale(2, BigDecimal.ROUND_DOWN));
		/** 总提现 **/
		Platformsum.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
		/** 总交易笔数 **/
		Platformsum.put("transactionCount", transactionCount);
		Platformsum.put("rechargeCount", rechargeCount);
		Platformsum.put("buyGoodsCount", buyGoodsCount);
		Platformsum.put("withdrawCount", withdrawCount);

		return Platformsum;
	}

	private Map getBrandsum(long brandId, Date startTimeDate, Date endTimeDate, String type, String status,
			String autoClearing) {
		Map Platformsum = new HashMap();
		/** 总入金 **/
		BigDecimal RechargeSum = null;
		/** 总购买 **/
		BigDecimal buyGoodsSum = null;
		/** 总提现 **/
		BigDecimal withdrawSum = null;
		/** 交易笔数 **/
		int transactionCount = 0;
		// 提现笔数
		int withdrawCount = 0;
		// 充值笔数
		int rechargeCount = 0;
		// 购买商品笔数
		int buyGoodsCount = 0;

		{
			type = "0";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			RechargeSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		{
			type = "1";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			buyGoodsSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		{
			type = "2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			withdrawSum = paymentOrderBusiness.findsumPaymentOrderBrand(brandId, str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		{
			type = "0,1,2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			transactionCount = paymentOrderBusiness.findsumPaymentOrderBrandCount(brandId, str1, str2, clear,
					startTimeDate, endTimeDate);
		}
		// 充值的交易笔数
		{
			type = "0";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			rechargeCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 购买商品的交易笔数
		{
			type = "1";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			buyGoodsCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}
		// 提现的交易笔数
		{
			type = "2";
			String[] str1 = type.split(",");
			String[] str2 = status.split(",");
			String[] clear = autoClearing.split(",");
			withdrawCount = paymentOrderBusiness.findsumPaymentOrderPlatformCount(str1, str2, clear, startTimeDate,
					endTimeDate);
		}

		Platformsum.put("RechargeSum", RechargeSum == null ? "0.00" : RechargeSum.setScale(2, BigDecimal.ROUND_DOWN));
		Platformsum.put("withdrawSum", withdrawSum == null ? "0.00" : withdrawSum.setScale(2, BigDecimal.ROUND_DOWN));
		Platformsum.put("buyGoodsSum", buyGoodsSum == null ? "0.00" : buyGoodsSum.setScale(2, BigDecimal.ROUND_DOWN));
		Platformsum.put("transactionCount", transactionCount);
		Platformsum.put("rechargeCount", rechargeCount);
		Platformsum.put("buyGoodsCount", buyGoodsCount);
		Platformsum.put("withdrawCount", withdrawCount);

		return Platformsum;
	}

	// 盛迪嘉通道——修改订单号
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/updateOrderCode")
	public @ResponseBody Object updateOrderCode(HttpServletRequest request,
			@RequestParam(value = "oldOrderCode") String orderCode,
			@RequestParam(value = "newOrderCode") String orderNo) {

		String substring = orderNo.substring(0, 10);

		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", orderCode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		String userid = resultObj.getString("userid");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("paymentchannel", "error url request!");
		url = uri.toString() + "/v1.0/paymentchannel/topup/sdj/querysdjid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
		jsonObject = JSONObject.fromObject(result);
		resultObj = jsonObject.getJSONObject("result");
		String sdjUserId = resultObj.getString("sdjUserId");

		PaymentOrder paymentOrder = null;

		if (substring.equals(sdjUserId)) {
			paymentOrder = paymentOrderBusiness.updatePaymentOrder(orderCode, orderNo);
		}

		Map map = new HashMap();
		if (paymentOrder != null) {

			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "修改成功");
			return map;
		} else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "修改失败");
			return map;
		}

	}

	/*
	 * public static void main(String[] args) throws Exception{ BigDecimal amount =
	 * new BigDecimal("600"); BigDecimal remainingAmount = amount;
	 * 
	 * Map map = new HashMap();
	 * 
	 * map.put("1", "0.2"); map.put("2", "0.2"); map.put("3", "0.3");
	 * 
	 * for(int i=1; i < 5; i++){ String rebate = (String)map.get(i+""); if(rebate !=
	 * null){
	 * 
	 * remainingAmount = remainingAmount.subtract(new
	 * BigDecimal(rebate).multiply(amount).setScale(2, BigDecimal.ROUND_HALF_UP)); }
	 * }
	 * 
	 * System.out.println(remainingAmount);
	 * 
	 * 
	 * 
	 * }
	 */
	public static Date getYYMMDateFromStr(String str) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date result = null;
		try {
			result = sdf.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
		}

		return result;
	}

	/*
	 * @RequestMapping(method=RequestMethod.POST,value=
	 * "/v1.0/transactionclear/payment/getExcel") public Object
	 * getExcel(HttpServletRequest request){ HSSFWorkbook workbook = new
	 * HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("统计表");
	 * createTitle(workbook, sheet); List<PaymentOrder> entities =
	 * paymentOrderBusiness.queryPaymentOrderAll(startTime, endTime, phone,
	 * ordercode, ordertype, orderstatus, brandid, pageAble)
	 * 
	 * //设置日期格式 HSSFCellStyle style=workbook.createCellStyle();
	 * style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
	 * 
	 * //新增数据行，并且设置单元格数据 int rowNum = 1; for (StatisticsInfo
	 * statisticsInfo:entities) {
	 * 
	 * HSSFRow row = sheet.createRow(rowNum);
	 * row.createCell(0).setCellValue(statisticsInfo.getId());
	 * row.createCell(1).setCellValue(statisticsInfo.getMoney().toString());
	 * row.createCell(2).setCellValue(statisticsInfo.getDescription()); HSSFCell
	 * cell = row.createCell(3); cell.setCellValue(statisticsInfo.getCurrentdate());
	 * cell.setCellStyle(style); rowNum++; }
	 * 
	 * //拼装blobName String fileName = "测试数据统计表.xlsx"; SimpleDateFormat dateFormat =
	 * new SimpleDateFormat("yyyyMMdd"); String dateTime = dateFormat.format(new
	 * Date()); String blobName = dateTime + "/" +
	 * UUID.randomUUID().toString().replaceAll("-", "") + "/" + fileName;
	 * 
	 * //获取或创建container CloudBlobContainer blobContainer =
	 * BlobHelper.getBlobContainer("temp", storageConfig); //设置文件类型，并且上传到azure blob
	 * try { CloudBlockBlob blob = blobContainer.getBlockBlobReference(blobName);
	 * ByteArrayOutputStream out = new ByteArrayOutputStream(); workbook.write(out);
	 * ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	 * 
	 * blob.upload(in, out.toByteArray().length); Map map = new HashMap();
	 * map.put("fileName", fileName); map.put("excelUrl", blob.getUri().toString());
	 * 
	 * ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrcode(),
	 * ResultStatusCode.OK.getErrmsg(), map); return resultMsg;
	 * 
	 * } catch (Exception e) { ResultMsg resultMsg = new
	 * ResultMsg(ResultStatusCode.SYSTEM_ERR.getErrcode(),
	 * ResultStatusCode.SYSTEM_ERR.getErrmsg(), null); return resultMsg; } }
	 * 
	 * 
	 * private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) { HSSFRow
	 * row = sheet.createRow(0);
	 * //设置列宽，setColumnWidth的第二个参数要乘以256，这个参数的单位是1/256个字符宽度 sheet.setColumnWidth(2,
	 * 12*256); sheet.setColumnWidth(3, 17*256);
	 * 
	 * //设置为居中加粗 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font =
	 * workbook.createFont(); font.setBold(true);
	 * style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setFont(font);
	 * 
	 * HSSFCell cell; cell = row.createCell(0); cell.setCellValue("序号");
	 * cell.setCellStyle(style);
	 * 
	 * cell = row.createCell(1); cell.setCellValue("金额"); cell.setCellStyle(style);
	 * 
	 * cell = row.createCell(2); cell.setCellValue("描述"); cell.setCellStyle(style);
	 * 
	 * cell = row.createCell(3); cell.setCellValue("日期"); cell.setCellStyle(style);
	 * }
	 */

	public String getNumberOrderCode() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date now = new Date();
		StringBuffer sb = new StringBuffer(sdf.format(now));
		Random random = new Random();
		for (int i = 0; i < 18; i++) {
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	public String getWFNumberOrderCode() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date now = new Date();
		StringBuffer sb = new StringBuffer(sdf.format(now));
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String substring = uuid.substring(0, 4);
		return sb.append(substring).toString();
	}

	// 获取待结算订单和成功订单
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/queryorderfailed")
	@ResponseBody
	public Object queryOrderFailed(HttpServletRequest request, @RequestParam(value = "userid") long userid) {
		Map map = new HashMap();
		String[] status = { "0", "1" };
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, paymentOrderBusiness.findOrderByUseridAndStatus(userid, status));
		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/add/credit/card/manager/order")
	public @ResponseBody Object createPaymentOrderToCreditCardManager(HttpServletRequest request,
			@RequestParam(value = "userId") String userIdStr, @RequestParam(value = "rate") String rateStr,
			@RequestParam(value = "type") String type, @RequestParam(value = "amount") String amountStr,
			@RequestParam(value = "realAmount") String realAmountStr,
			@RequestParam(value = "creditCardNumber") String creditCardNumber,
			@RequestParam(value = "channelTag") String channelTag, @RequestParam(value = "orderCode") String orderCode,
			@RequestParam(value = "serviceCharge") String serviceCharge,
			@RequestParam(value = "description", required = false, defaultValue = "") String description,
			@RequestParam(value = "remark", required = false, defaultValue = "") String remark) {
		userIdStr = userIdStr.trim();
		rateStr = rateStr.trim();
		amountStr = amountStr.trim();
		realAmountStr = realAmountStr.trim();
		serviceCharge = serviceCharge.trim();
		orderCode = orderCode.trim();
		type = type.trim();
		channelTag = channelTag.trim();
		Map map = new HashMap();
		long userId = Long.valueOf(userIdStr);
		BigDecimal rate = new BigDecimal(rateStr);

		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/find/by/userid";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", userIdStr);
		String resultString;
		JSONObject resultJSONObject;
		try {
			resultString = restTemplate.postForObject(url, requestEntity, String.class);
			resultJSONObject = JSONObject.fromObject(resultString);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成订单失败,服务器正忙,请稍后重试!");
			return map;
		}
		LOG.info("RESULT============/v1.0/user/find/by/userid:" + resultString);
		if (!CommonConstants.SUCCESS.equals(resultJSONObject.getString(CommonConstants.RESP_CODE))) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成订单失败,无该用户数据!");
			return map;
		}

		resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
		long brandId = resultJSONObject.getLong("brandId");
		String phone = resultJSONObject.getString("phone");
		String brandName = resultJSONObject.getString("brandname");

		PaymentOrder paymentOrder = new PaymentOrder();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/channel/query";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channel_tag", channelTag);
		resultString = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================/v1.0/user/channel/query:" + resultString);
		resultJSONObject = JSONObject.fromObject(resultString);
		resultJSONObject = resultJSONObject.getJSONObject(CommonConstants.RESULT);
		long channelId = resultJSONObject.getLong("id");
		String channelName = resultJSONObject.getString("name");
		String channelTag2 = resultJSONObject.getString("channelTag");
		String channelType = resultJSONObject.getString("channelType");
		String autoClearing = resultJSONObject.getString("autoclearing");
		String costRateStr = resultJSONObject.getString("costRate");
		BigDecimal costRate = new BigDecimal(costRateStr);
		if (!(BigDecimal.ZERO.compareTo(rate) == 0)) {
			if (costRate.compareTo(rate) > 0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "下单失败,您的费率有异常,请联系管理员!");
				return map;
			}
		}
		paymentOrder.setChannelid(channelId);
		paymentOrder.setChannelname(channelName);
		paymentOrder.setChannelTag(channelTag2);
		paymentOrder.setBankcard(creditCardNumber);
		paymentOrder.setAutoClearing(autoClearing);
		paymentOrder.setRate(rate);
		paymentOrder.setChannelType(channelType);

		LinkedMultiValueMap<String, String> requestEntity2 = new LinkedMultiValueMap<String, String>();
		requestEntity2.add("channel_id", channelId + "");
		requestEntity2.add("user_id", userId + "");
		Map<String, Object> restTemplateDoPost = restTemplateUtil.restTemplateDoPost("user",
				"/v1.0/user/channel/rate/query/userid", requestEntity2);
		if (!CommonConstants.SUCCESS.equals(restTemplateDoPost.get(CommonConstants.RESP_CODE))) {
			return restTemplateDoPost;
		}
		resultJSONObject = (JSONObject) restTemplateDoPost.get(CommonConstants.RESULT);
		LOG.info("==========/v1.0/user/channel/rate/query/userid:" + resultJSONObject);
		String withdrawFee = resultJSONObject.getString("withdrawFee");
		String extraFee = resultJSONObject.getString("extraFee");

		BigDecimal newwithdrawFee = withdrawFee == null || withdrawFee.equalsIgnoreCase("")
				|| withdrawFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(withdrawFee);
		BigDecimal newextraFee = extraFee == null || extraFee.equalsIgnoreCase("") || extraFee.equalsIgnoreCase("null")
				? BigDecimal.ZERO
				: new BigDecimal(extraFee);

		paymentOrder.setExtraFee(newwithdrawFee.add(newextraFee));
		paymentOrder.setCostfee(newwithdrawFee);
		
		paymentOrder.setAmount(new BigDecimal(amountStr));
		paymentOrder.setRealAmount(new BigDecimal(realAmountStr));
		paymentOrder.setUserid(userId);
		paymentOrder.setBrandid(brandId);
		paymentOrder.setBrandname(brandName);
		paymentOrder.setRemark(remark);
		paymentOrder.setCreateTime(new Date());
		paymentOrder.setUpdateTime(new Date());
		paymentOrder.setDesc(description);
		paymentOrder.setOrdercode(orderCode);
		paymentOrder.setPhone(phone);
		paymentOrder.setType(type);
		paymentOrder.setStatus(CommonConstants.ORDER_READY);

		LOG.info("RESULT================" + paymentOrder.getOrdercode() + "************************************");
		try {
			paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成订单异常");
			return map;
		}
		LOG.info("RESULT================" + paymentOrder.toString() + "************************************");
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, paymentOrder);
		return map;
	}

	// 查询订单添加失败信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/update/remark")
	public @ResponseBody Object addErrorMsg(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode, @RequestParam(value = "remark") String remark) {
		Map map = new HashMap();
		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(ordercode);
		if (paymentOrder == null) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "订单查询失败");
		} else {
			paymentOrderBusiness.addErrorByOrderCode(ordercode, remark);
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
		}
		return map;
	}

	
	
	//根据userId、时间、channelTag、orderStatus查询交易金额
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/querytransaction/sumamount")
	public @ResponseBody Object getEveryDayMaxLimitAmount(HttpServletRequest request,
			@RequestParam(value = "userId") String userId, 
			@RequestParam(value = "channelTag") String channelTag,
			@RequestParam(value = "orderStatus") String orderStatus
			) {
		
		
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date date = new Date();
		
		LOG.info("date1====" + sdf1.format(zero));
		LOG.info("date2====" + sdf1.format(date));
		
		BigDecimal everyDayMaxLimit;
		try {
			everyDayMaxLimit = paymentOrderBusiness.getEveryDayMaxLimit(sdf1.format(zero), sdf1.format(date), channelTag, orderStatus, Long.valueOf(userId));
			LOG.info("查询结果为======"+everyDayMaxLimit);
			if(everyDayMaxLimit == null) {
				everyDayMaxLimit = BigDecimal.ZERO;
			}
			LOG.info("重新赋值的结果为======"+everyDayMaxLimit);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			
			return ResultWrap.init(CommonConstants.FALIED, "查询失败");
		}
		
		return ResultWrap.init(CommonConstants.SUCCESS, "查询成功", everyDayMaxLimit);
	
	}
	
	
	
	// 通道成功率
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/finduccess")
	public @ResponseBody Object findSuccessRate(HttpServletRequest request,
			/**
			 * 贴牌筛选
			 */
			@RequestParam(value = "brand_id", defaultValue = "-1", required = false) long brandId, /***
																									 * 时间筛选
																									 **/
			@RequestParam(value = "starttime", required = false) String startTime,
			@RequestParam(value = "endtime", required = false) String endTime) {
		Date StartTimeDate = null;
		if (startTime != null && startTime.trim().length() > 0) {
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null;
		if (endTime != null && endTime.trim().length() > 0) {
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}

		if ((startTime == null || startTime.trim().length() == 0)
				&& (endTime == null || endTime.trim().length() == 0)) {
			StartTimeDate = DateUtil.getDateFromStr(DateUtil.getDateFromStr(new Date()));
		}

		List<PaymentOrderNumber> SuccessRate = paymentOrderBusiness.findOrderSuccessRate(brandId, StartTimeDate,
				endTimeDate);

		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, SuccessRate);

		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/payment/deletepayment/byordercode")
	public @ResponseBody Object deletePaymentByOrdercode(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) {

		Map map = new HashMap();

		paymentOrderBusiness.deletePaymentOrderByOrderCode(ordercode);

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;

	}

	/*
	 * @RequestMapping(method = RequestMethod.POST, value =
	 * "/v1.0/transactionclear/payment/deletepayment/bylist") public @ResponseBody
	 * Object deletePaymentByList(HttpServletRequest request,
	 * 
	 * @RequestParam(value = "startTime", required = false) String startTime,
	 * 
	 * @RequestParam(value = "endTime", required = false) String endTime,
	 * 
	 * @RequestParam(value = "channelTag", required = false) String[] channelTag,
	 * 
	 * @RequestParam(value = "status", required = false) String status,
	 * 
	 * @RequestParam(value = "remark", required = false) String remark) {
	 * 
	 * Map map = new HashMap();
	 * 
	 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new
	 * Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
	 * calendar.add(Calendar.DAY_OF_MONTH, +1); date = calendar.getTime();
	 * 
	 * Date date2 = new Date();
	 * 
	 * LOG.info("====" + sdf.format(date)); LOG.info("====" + sdf.format(date2));
	 * 
	 * String[] strings = { "LD_QUICK", "LF_QUICK" };
	 * 
	 * try { List<PaymentOrder> list =
	 * paymentOrderBusiness.findOrderByTimeAndChannelTagAndStatusAndRemark(sdf.
	 * format(date2), sdf.format(date), strings, status);
	 * 
	 * LOG.info("=============" + list.size());
	 * 
	 * // paymentOrderBusiness.deletePaymentOrder(list); } } catch (Exception e) {
	 * LOG.info("操作失败=====" + e); map.put(CommonConstants.RESP_CODE,
	 * CommonConstants.FALIED); map.put(CommonConstants.RESP_MESSAGE, "失败"); return
	 * map; }
	 * 
	 * map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
	 * map.put(CommonConstants.RESP_MESSAGE, "成功"); return map;
	 * 
	 * }
	 */

	// 根据订单号查询用户进件的结算卡
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/findbankcard/byordercode")
	public @ResponseBody Object findBankCardByOrderCode(@RequestParam(value = "ordercode") String orderCode) {
		Map<String, String> map = new HashMap<String, String>();

		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);

		String object = null;
		String phone = paymentOrder.getPhone();
		String channelTag = paymentOrder.getChannelTag();
		long userid = paymentOrder.getUserid();

		if ("UMP_PAY".equals(channelTag)) {

			RestTemplate restTemplate = new RestTemplate();
			URI uri = util.getServiceUrl("user", "error url request!");
			String url = uri.toString() + "/v1.0/user/bank/default/userid";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("user_id", userid + "");
			String result;
			JSONObject jsonObject;
			JSONObject resultObj = null;
			try {
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("接口/v1.0/user/bank/default/userid--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				LOG.error("查询订单有误=====");
				e.printStackTrace();
				LOG.error(ExceptionUtil.errInfo(e));
				map.put(CommonConstants.RESP_CODE, "failed");
				map.put(CommonConstants.RESP_MESSAGE, "查询订单信息有误");
				return map;
			}

			object = resultObj.getString("cardNo");

		} else {

			RestTemplate restTemplate = new RestTemplate();
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/querybankcard/byphone/andchanneltag";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("phone", phone);
			requestEntity.add("channel_tag", channelTag);
			String result;
			JSONObject jsonObject;
			JSONObject resultObj = null;
			try {
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("接口/v1.0/paymentchannel/querybankcard/byphone/andchanneltag--RESULT================" + result);
				jsonObject = JSONObject.fromObject(result);
				// resultObj = jsonObject.getJSONObject("result");
				object = (String) jsonObject.get("result");
			} catch (Exception e) {
				LOG.error("查询订单有误=====");
				e.printStackTrace();
				LOG.error(ExceptionUtil.errInfo(e));
				map.put(CommonConstants.RESP_CODE, "failed");
				map.put(CommonConstants.RESP_MESSAGE, "查询订单信息有误");
				return map;
			}

		}

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, object);
		map.put(CommonConstants.RESP_MESSAGE, "成功");

		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/earning/report")
	public @ResponseBody Object earningReport(HttpServletRequest request, @RequestParam(value = "phone") String phone,
			@RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = false) String endTime) {

		Map<String, Object> map = new HashMap<String, Object>();

		boolean hasKey = false;
		String key = "/v1.0/transactionclear/earning/report:phone=" + phone + ";startTime=" + startTime + ";endTime="
				+ endTime;
		ValueOperations<String, Object> operations = redisTemplate.opsForValue();
		hasKey = redisTemplate.hasKey(key);
		if (hasKey) {
			return operations.get(key);
		}

		Map<String, Object> map2 = null;
		try {
			String url = "http://user/v1.0/user/realtion/find/user/member/byphone";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("phone", phone);
			requestEntity.add("start_time", startTime);
			requestEntity.add("end_time", endTime);
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("接口/v1.0/user/realtion/find/user/member/byphone======result==========" + result);
			JSONObject fromObject = JSONObject.fromObject(result);
			// 间推
			JSONArray jsonArray1 = fromObject.getJSONArray("list1");
			// 直推
			JSONArray jsonArray2 = fromObject.getJSONArray("list2");
			long l;
			long[] long1 = new long[jsonArray1.size()];
			for (int i = 0; i < jsonArray1.size(); i++) {
				l = jsonArray1.getLong(i);
				long1[i] = l;
			}

			Map<String, Object> maps = new HashMap<String, Object>();

			maps = (Map<String, Object>) paymentOrderBusiness.queryPaymentOrderSumAmountByUserId(long1, startTime,
					endTime);

			// 充值的金额
			BigDecimal jiantuirechargeAmount = (BigDecimal) maps.get("big");
			// 购买产品的金额
			BigDecimal jiantuibuyAmount = (BigDecimal) maps.get("big1");
			// 还款的金额
			BigDecimal jiantuirepaymentAmount = (BigDecimal) maps.get("big2");

			LOG.info("jiantuirechargeAmount=====" + jiantuirechargeAmount);
			LOG.info("jiantuibuyAmount=====" + jiantuibuyAmount);
			LOG.info("jiantuirepaymentAmount=====" + jiantuirepaymentAmount);

			long l2;
			long[] long2 = new long[jsonArray2.size()];

			for (int j = 0; j < jsonArray2.size(); j++) {
				l2 = jsonArray2.getLong(j);
				long2[j] = l2;
			}

			Map<String, Object> map1 = new HashMap<String, Object>();

			map1 = (Map<String, Object>) paymentOrderBusiness.queryPaymentOrderSumAmountByUserId(long2, startTime,
					endTime);

			// 充值的金额
			BigDecimal zhituirechargeAmount = (BigDecimal) map1.get("big");
			// 购买产品的金额
			BigDecimal zhituibuyAmount = (BigDecimal) map1.get("big1");
			// 还款的金额
			BigDecimal zhituirepaymentAmount = (BigDecimal) map1.get("big2");

			LOG.info("zhituirechargeAmount=====" + zhituirechargeAmount);
			LOG.info("zhituibuyAmount=====" + zhituibuyAmount);
			LOG.info("zhituirepaymentAmount=====" + zhituirepaymentAmount);

			// 个人分润总和
			BigDecimal profitAmount = profitRecordBusiness.queryProfitRecordSumAcqAmountByPhone(phone, startTime,
					endTime);
			LOG.info("profitAmount=======" + profitAmount);

			// 个人返佣总和
			BigDecimal distributionAmount = distributionBusiness.queryDistributionSumAcqAmountByPhone(phone, startTime,
					endTime);
			LOG.info("distributionAmount=======" + distributionAmount);

			map2 = new HashMap<String, Object>();

			map2.put("jiantuiNum", jsonArray1.size());// 间推人数
			map2.put("zhituiNum", jsonArray2.size());// 直推人数
			map2.put("jiantuirechargeAmount", jiantuirechargeAmount);// 间推充值总金额
			map2.put("jiantuibuyAmount", jiantuibuyAmount);// 间推购买总金额
			map2.put("jiantuirepaymentAmount", jiantuirepaymentAmount);// 间推还款总金额
			map2.put("zhituirechargeAmount", zhituirechargeAmount);// 直推充值总金额
			map2.put("zhituibuyAmount", zhituibuyAmount);// 直推购买总金额
			map2.put("zhituirepaymentAmount", zhituirepaymentAmount);// 直推还款总金额
			map2.put("profitAmount", profitAmount);// 个人分润总金额
			map2.put("distributionAmount", distributionAmount);// 个人返佣总金额
		} catch (RestClientException e) {
			LOG.info("查询失败======");
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询失败");

			return map;
		}

		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, map2);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");

		operations.set(key, map, 5, TimeUnit.HOURS);
		return map;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/create/outpaymentorder")
	public @ResponseBody Object createOutOfPaymentOrder(HttpServletRequest request,
			@RequestParam(value = "userId") String userId, @RequestParam(value = "amount") String amount,
			@RequestParam(value = "channelTag") String channeltag,
			// 出款卡
			@RequestParam(value = "bankCard") String bankcard,
			// 到账卡
			@RequestParam(value = "debitBankCard") String debitBankCard,
			@RequestParam(value = "description", defaultValue = "", required = false) String description,
			@RequestParam(value = "outNotifyUrl", defaultValue = "", required = false) String outNotifyUrl,
			@RequestParam(value = "outReturnUrl", defaultValue = "", required = false) String outReturnUrl,
			@RequestParam(value = "outOrderCode") String outOrderCode,
			@RequestParam(value = "remark", defaultValue = "", required = false) String remark) {
		Map<String, Object> verifyMoney = AuthorizationHandle.verifyMoney(amount, 2, BigDecimal.ROUND_HALF_UP);
		if (!CommonConstants.SUCCESS.equals(verifyMoney.get(CommonConstants.RESP_CODE))) {
			return verifyMoney;
		}

		PaymentOrder paymentOrder = paymentOrderBusiness.findByOutMerOrdercode(outOrderCode);
		if (paymentOrder != null) {
			return ResultWrap.init(CommonConstants.FALIED, "订单已存在");
		}

		String url = "http://user/v1.0/user/channel/rate/query/by/channelTag";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userId", userId + "");
		requestEntity.add("channelTag", channeltag);
		String resultString = restTemplate.postForObject(url, requestEntity, String.class);
		JSONObject resultJSON = JSONObject.fromObject(resultString);

		if (!CommonConstants.SUCCESS.equals(resultJSON.getString(CommonConstants.RESP_CODE))) {
			return ResultWrap.init(CommonConstants.FALIED, resultJSON.getString(CommonConstants.RESP_MESSAGE));
		}

		JSONObject channelRateJSON = resultJSON.getJSONObject(CommonConstants.RESULT);
		JSONObject userJSON = resultJSON.getJSONObject("user");
		Long brandId = userJSON.getLong("brandId");
		String brandName = userJSON.getString("brandname");
		String phone = userJSON.getString("phone");

		JSONObject channelJSON = resultJSON.getJSONObject("channel");
		paymentOrder = new PaymentOrder();

		long channelId = channelJSON.getLong("id");
		String channelName = channelJSON.getString("name");
		String channelTag = channelJSON.getString("channelTag");
		String channelType = channelJSON.getString("channelType");
		String autoclearing = channelJSON.getString("autoclearing");
		// 成本费率
		String costRateStr = channelJSON.getString("costRate");

		double costRate = Double.valueOf(costRateStr);

		String rate = channelRateJSON.getString("rate");
		double userRate = Double.valueOf(rate);
		// 当用户费率小于成本费率时不生成订单!
		if (userRate < costRate) {
			LOG.error("用户费率低于成本费率了!!!生成订单失败=============================用户userId:" + userId);
			return ResultWrap.init(CommonConstants.FALIED, "下单失败,原因:费率异常!");
		}

		String extraFee = channelRateJSON.getString("extraFee");
		String withdrawFee = channelRateJSON.getString("withdrawFee");
		paymentOrder.setChannelid(channelId);
		paymentOrder.setChannelname(channelName);
		paymentOrder.setChannelTag(channelTag);
		paymentOrder.setBankcard(bankcard);
		paymentOrder.setDebitBankCard(debitBankCard);
		paymentOrder.setAutoClearing(autoclearing);
		paymentOrder.setRate(new BigDecimal(rate));
		BigDecimal newextraFee = extraFee == null || extraFee.equalsIgnoreCase("") || extraFee.equalsIgnoreCase("null")
				? BigDecimal.ZERO
				: new BigDecimal(extraFee);
		BigDecimal newwithdrawFee = withdrawFee == null || withdrawFee.equalsIgnoreCase("")
				|| withdrawFee.equalsIgnoreCase("null") ? BigDecimal.ZERO : new BigDecimal(withdrawFee);

		paymentOrder.setExtraFee(newextraFee.add(newwithdrawFee));
		paymentOrder.setCostfee(newwithdrawFee);
		paymentOrder.setChannelType(channelType);
		/** 充值到账要扣除手续费的 */
		BigDecimal fee = new BigDecimal("0.00");
		if ("0".equals(autoclearing.trim())) {
			fee = new BigDecimal(amount).multiply(new BigDecimal(rate));
		} else {
			fee = new BigDecimal(amount).multiply(new BigDecimal(rate)).add(paymentOrder.getExtraFee());
		}
		paymentOrder.setRealAmount(new BigDecimal(amount).subtract(fee).setScale(2, BigDecimal.ROUND_HALF_DOWN));

		paymentOrder.setAmount(new BigDecimal(amount));
		paymentOrder.setUserid(Long.valueOf(userId));
		paymentOrder.setBrandid(brandId);
		paymentOrder.setBrandname(brandName);
		if (remark == null) {
			paymentOrder.setRemark("");
		} else {
			paymentOrder.setRemark(remark);
		}
		paymentOrder.setCreateTime(new Date());
		paymentOrder.setUpdateTime(new Date());
		paymentOrder.setDesc(description);
		paymentOrder.setOrdercode(UUIDGenerator.getDateTimeOrderCode());

		paymentOrder.setPhone(phone);
		paymentOrder.setType("0");

		paymentOrder.setOutMerOrdercode(outOrderCode);
		paymentOrder.setOutNotifyUrl(outNotifyUrl);
		paymentOrder.setOutReturnUrl(outReturnUrl);
		paymentOrder.setStatus(CommonConstants.ORDER_READY);
		paymentOrder = paymentOrderBusiness.mergePaymentOrder(paymentOrder);
		LOG.info("RESULT================" + paymentOrder.toString() + "************************************");
		return ResultWrap.init(CommonConstants.SUCCESS, "下单成功", paymentOrder);
	}

	// @Scheduled(cron = "0 0 0/1 * * ?")
	@Scheduled(cron = "0 0/4 * * * ?")
	public void scheduleFindPaymentOrder() {
		if ("true".equals(scheduleTaskOnOff)) {
			updateYBQuickOrderStatus();
			LOG.info("继续下一个任务=======");
			findPaymentOrderBySomething();
		}
	}

	@Scheduled(cron = "0 0/2 * * * ?")
	public void schedulequeryOrderByRemark() {
		if ("true".equals(scheduleTaskOnOff)) {
			queryOrderByRemark();
		}
	}

	@Scheduled(cron = "0 00 06 * * ?")
	public void scheduleupdateChannelPaymentStatus() {
		if ("true".equals(scheduleTaskOnOff)) {
			updateChannelPaymentStatus();
		}
	}

	/*
	 * @Scheduled(cron = "0 0/2 * * * ?") public void scheduleupdateYBQuickRemark()
	 * { if ("true".equals(scheduleTaskOnOff)) { updateYBQuickOrderStatus(); } }
	 */

	// 将未请求的订单状态修改为已取消
	public void findPaymentOrderBySomething() {

		LOG.info("将未请求的订单状态修改为已取消 开始执行======");

		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +1);
		date = calendar.getTime();

		/*Date date1 = new Date();
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar1.add(Calendar.DAY_OF_MONTH, -1);
		date1 = calendar1.getTime();*/
		
		Calendar calendar1 = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date date2 = new Date();
		/*Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);
		calendar2.add(Calendar.MINUTE, -5);
		date2 = calendar2.getTime();*/
		
		
		LOG.info("date====" + sdf1.format(date));
		LOG.info("date1====" + sdf1.format(zero));
		LOG.info("date2====" + sdf1.format(date2));

		String[] strings = { "XJY_QUICK1", "LF_QUICK", "SDJ_QUICK", "CJ_QUICK", "YB_QUICK", "YB_PAY" };

		List<PaymentOrder> list = paymentOrderBusiness.findOrderByTimeAndChannelTagAndStatus(sdf1.format(zero),
				sdf1.format(date2), strings, "0", "");

		LOG.info("需要改成 已取消的=============" + list.size());

		LOG.info("需要改成 已取消的=============" + list.size());

		// paymentOrderBusiness.deletePaymentOrder(list);

		// 修改订单状态为 已取消
		if (list != null || list.size() > 0) {
			for (PaymentOrder po : list) {
				PaymentOrder queryPaymentOrderBycode = paymentOrderBusiness.queryPaymentOrderBycode(po.getOrdercode());

				queryPaymentOrderBycode.setStatus("2");

				paymentOrderBusiness.mergePaymentOrder(queryPaymentOrderBycode);
			}
		}

		List<PaymentOrder> list1 = paymentOrderBusiness
				.findOrderByTimeAndChannelTagAndStatusAndRemark(sdf1.format(zero), sdf1.format(date2), strings, "2");

		LOG.info("需要改成 待完成的=============" + list1.size());
		// 修改订单状态为 待完成
		if (list1 != null || list1.size() > 0) {
			for (PaymentOrder po : list1) {
				PaymentOrder queryPaymentOrderBycode1 = paymentOrderBusiness.queryPaymentOrderBycode(po.getOrdercode());

				queryPaymentOrderBycode1.setStatus("0");

				paymentOrderBusiness.mergePaymentOrder(queryPaymentOrderBycode1);
			}
		}

		LOG.info("将未请求的订单状态修改为已取消 执行完成======");
	}

	// 扫描订单描述是否代表额度已满
	public void queryOrderByRemark() {

		LOG.info("扫描订单描述是否代表额度已满 开始执行======");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now = new Date();
		Date before = new Date(now.getTime() - 120000);
		// Date before = new Date(now.getTime()-600000);

		String str1 = "XJY_QUICK1";
		String str2 = "LF_QUICK";

		String[] strings = { str1, str2 };

		List<PaymentOrder> list = paymentOrderBusiness
				.findOrderByTimeAndChannelTagAndStatusAndRemark(sdf.format(before), sdf.format(now), strings, "0");

		LOG.info("查询出来的结果======" + list.size());

		if (list != null || list.size() > 0) {

			boolean isTrueStr1 = true;
			boolean isTrueStr2 = true;

			for (PaymentOrder po : list) {

				PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(po.getOrdercode());

				if (str1.equals(paymentOrder.getChannelTag())) {
					if ("交易拒绝,您的交易金额超过网银交易金额限制或该通道额度已达上限!".equals(paymentOrder.getRemark().trim())
							|| "2308 : 交易金额超限或无效".equals(paymentOrder.getRemark().trim())) {

						RestTemplate restTemplate = new RestTemplate();
						URI uri = util.getServiceUrl("user", "error url request!");
						String url = uri.toString() + "/v1.0/user/channel/update/paymentstatus";
						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("channelTag", str1);
						requestEntity.add("paymentStatus", "0");
						String result = restTemplate.postForObject(url, requestEntity, String.class);
						LOG.info("RESULT================" + result);

						isTrueStr1 = false;
					}

				} else {
					if ("100003 : 通道不可使用或额度已用完".equals(paymentOrder.getRemark())) {

						RestTemplate restTemplate = new RestTemplate();
						URI uri = util.getServiceUrl("user", "error url request!");
						String url = uri.toString() + "/v1.0/user/channel/update/paymentstatus";
						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("channelTag", str2);
						requestEntity.add("paymentStatus", "0");
						String result = restTemplate.postForObject(url, requestEntity, String.class);
						LOG.info("RESULT================" + result);

						isTrueStr2 = false;

					}

				}

				if (isTrueStr1 == false && isTrueStr2 == false) {
					break;
				}

			}

			/*
			 * for(PaymentOrder po : list) {
			 * 
			 * PaymentOrder paymentOrder =
			 * paymentOrderBusiness.queryPaymentOrderBycode(po.getOrdercode());
			 * 
			 * if(paymentOrder.getChannelTag().equals(str2) &&
			 * paymentOrder.getRemark().equals("100003 : 通道不可使用或额度已用完")) {
			 * 
			 * RestTemplate restTemplate = new RestTemplate(); URI uri =
			 * util.getServiceUrl("user", "error url request!"); String url = uri.toString()
			 * + "/v1.0/user/channel/update/paymentstatus"; MultiValueMap<String, String>
			 * requestEntity = new LinkedMultiValueMap<String, String>();
			 * requestEntity.add("channelTag", str2); requestEntity.add("paymentStatus",
			 * "0"); String result = restTemplate.postForObject(url, requestEntity,
			 * String.class); LOG.info("RESULT================" + result);
			 * 
			 * break; }
			 * 
			 * }
			 */

		}

		LOG.info("扫描订单描述是否代表额度已满 执行完成======");
	}

	// 每天早上6点将通道的额度限制开关打开
	public void updateChannelPaymentStatus() {

		LOG.info("每天早上6点执行======");

		String str1 = "XJY_QUICK1";
		String str2 = "LF_QUICK";

		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("user", "error url request!");
		String url = uri.toString() + "/v1.0/user/channel/update/paymentstatus";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channelTag", str1);
		requestEntity.add("paymentStatus", "1");
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/channel/update/paymentstatus";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("channelTag", str2);
		requestEntity.add("paymentStatus", "1");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("RESULT================" + result);
	}

	// 银联5===================================================
	//@Scheduled(cron = "0 0/3 * * * ?")
	public void updateYBQuickOrderStatus() {

		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		/*Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();*/

		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
		
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date date1 = new Date();
		/*Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar1.add(Calendar.MINUTE, -10);
		date1 = calendar1.getTime();*/

		LOG.info("====" + sdf1.format(zero));
		LOG.info("====" + sdf1.format(date1));

		String[] status = {"0", "2"};
		
		List<String> findYBpayOrder = paymentOrderBusiness.findYBpayOrder(sdf1.format(zero), sdf1.format(date1), "YB_PAY", status);

		//List<String> findYBpayOrder =paymentOrderBusiness.findYBpayOrder("2018-05-31", "2018-06-01", "YB_PAY", status);

		LOG.info("银联5需要查询的订单数======" + findYBpayOrder.size());

		HttpServletRequest request = null;

		if (findYBpayOrder != null && findYBpayOrder.size() > 0) {

			for (String orderCode : findYBpayOrder) {

				try {
					queryOrderCode(request, orderCode);
				} catch (Exception e) {
					e.printStackTrace();

					continue;
				}

			}

			LOG.info("银联5查询订单任务执行完成======");
		} else {
			LOG.info("银联5暂无执行任务======");
		}

		// ===========

		List<String> findYBquickOrder = paymentOrderBusiness.findYBpayOrder(sdf1.format(zero), sdf1.format(date1), "YB_QUICK", status);

		//List<String> findYBquickOrder = paymentOrderBusiness.findYBpayOrder("2018-05-31", "2018-06-01", "YB_QUICK",  status);

		LOG.info("银联4需要查询的订单数======" + findYBquickOrder.size());

		if (findYBquickOrder != null && findYBquickOrder.size() > 0) {

			for (String orderCode : findYBquickOrder) {

				try {
					queryOrderCodeYBQuick(request, orderCode);
				} catch (Exception e) {
					e.printStackTrace();

					continue;
				}

			}

			LOG.info("银联4查询订单任务执行完成======");
		} else {
			LOG.info("银联4暂无执行任务======");
		}

	}

	// 银联5的订单查询接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/query/ordercode")
	public @ResponseBody Object queryOrderCode(HttpServletRequest request,
			@RequestParam(value = "ordercode") String orderCode) {

		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);

		param2[0].setValue("10015703385");
		param2[1].setValue(orderCode);
		param2[2].setValue(paymentOrder.getCreateTime().toString());
		param2[3].setValue("1");
		param2[param2.length - 1].setValue(hmacSign2());
		PostMethod postMethod = new PostMethod("https://skb.yeepay.com/skb-app/tradeReviceQuery.action");
		HttpClient client = new HttpClient();
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		postMethod.setRequestBody(param2);
		String code = null;
		String balance = null;
		int status2;
		try {
			status2 = client.executeMethod(postMethod);
			LOG.info("==========status2==========" + status2);
			String response = postMethod.getResponseBodyAsString();
			LOG.info("==========response==========" + response);

			JSONObject fromObject = JSONObject.fromObject(response);

			code = (String) fromObject.get("code");

			if ("0000".equals(code)) {

				JSONArray jsonArray = fromObject.getJSONArray("tradeReceives");
				if(jsonArray == null || jsonArray.size() == 0) {
					LOG.info("tradeReceives为空======");
					return null;
				}
				
				JSONObject jsonObject = null;
				for (int i = 0; i < jsonArray.size(); i++) {

					jsonObject = (JSONObject) jsonArray.get(i);

				}

				LOG.info("jsonObject======" + jsonObject);

				String status = jsonObject.getString("status");
				String errorMessage = "";

				if (jsonObject.has("errorMessage")) {
					errorMessage = jsonObject.getString("errorMessage");
				}
				/*
				 * else { errorMessage = "未知失败原因,请联系易宝客服"; }
				 */

				// LOG.info("status======"+status);
				// LOG.info("errorMessage======"+errorMessage);

				if ("FAIL".equalsIgnoreCase(status)) {
					if (!errorMessage.contains("支付记录不存在") && !"".equals(errorMessage)) {

						addErrorMsg(request, orderCode, errorMessage);
						
						updatePaymentOrder(request, orderCode, "0", "", "");
						
						return null;
					} else {

						// updatePaymentOrder(request, orderCode, "2", "", "");
						return null;
					}

				} else if ("INIT".equalsIgnoreCase(status)) {

					// updatePaymentOrder(request, orderCode, "2", "", "");
					return null;
				}

			} else {
				LOG.info("请求查询订单失败======");
				return null;
			}

		} catch (IOException e) {
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			return null;
		}

		return null;
	}

	private static NameValuePair[] param2 = {
			// 大商户编号
			new NameValuePair("mainCustomerNumber", ""),
			/*
			 * // 小商户编号 new NameValuePair("customerNumber", ""),
			 */
			// 出款订单号
			new NameValuePair("requestId", ""),

			new NameValuePair("createTimeBegin", ""), new NameValuePair("pageNo", ""),
			// 签名串
			new NameValuePair("hmac", ""),

	};

	private static String hmacSign2() {
		StringBuilder hmacStr = new StringBuilder();
		for (NameValuePair nameValuePair : param2) {
			if (nameValuePair.getName().equals("hmac")) {
				continue;
			}
			hmacStr.append(nameValuePair.getValue() == null ? "" : nameValuePair.getValue());

		}

		String hmac = Digest.hmacSign(hmacStr.toString(),
				"oF34lTpB9x9v05D2B0eP1r18EDX71THlT4Go5X0s6V7T85gh2J63j30iPh38");

		return hmac;
	}

	// 银联5=========================================================end

	// 银联4的订单查询接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/query/ordercode/ybquick")
	public @ResponseBody Object queryOrderCodeYBQuick(HttpServletRequest request,
			@RequestParam(value = "ordercode") String orderCode) {

		PaymentOrder paymentOrder = paymentOrderBusiness.queryPaymentOrderBycode(orderCode);

		param2[0].setValue("10015053457");
		param2[1].setValue(orderCode);
		param2[2].setValue(paymentOrder.getCreateTime().toString());
		param2[3].setValue("1");
		param2[param2.length - 1].setValue(hmacSign());
		PostMethod postMethod = new PostMethod("https://skb.yeepay.com/skb-app/tradeReviceQuery.action");
		HttpClient client = new HttpClient();
		postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		postMethod.setRequestBody(param2);
		String code = null;
		String balance = null;
		int status2;
		try {
			status2 = client.executeMethod(postMethod);
			// LOG.info("==========status2==========" + status2);
			String response = postMethod.getResponseBodyAsString();
			// LOG.info("==========response==========" + response);

			JSONObject fromObject = JSONObject.fromObject(response);

			code = (String) fromObject.get("code");

			if ("0000".equals(code)) {

				JSONArray jsonArray = fromObject.getJSONArray("tradeReceives");
				
				if(jsonArray == null || jsonArray.size() == 0) {
					LOG.info("tradeReceives为空======");
					return null;
				}
				
				JSONObject jsonObject = null;
				for (int i = 0; i < jsonArray.size(); i++) {

					jsonObject = (JSONObject) jsonArray.get(i);

				}

				LOG.info("jsonObject======" + jsonObject);

				String status = jsonObject.getString("status");
				String errorMessage = "";

				if (jsonObject.has("errorMessage")) {
					errorMessage = jsonObject.getString("errorMessage");
				}
				/*
				 * else { errorMessage = "未知失败原因,请联系易宝客服"; }
				 */

				// LOG.info("status======"+status);
				// LOG.info("errorMessage======"+errorMessage);

				if ("FAIL".equalsIgnoreCase(status)) {
					if (!errorMessage.contains("支付记录不存在") && !"".equals(errorMessage)) {

						addErrorMsg(request, orderCode, errorMessage);

						updatePaymentOrder(request, orderCode, "0", "", "");
						
						return null;
					} else {

						// updatePaymentOrder(request, orderCode, "2", "", "");
						return null;
					}

				} else if ("INIT".equalsIgnoreCase(status)) {

					// updatePaymentOrder(request, orderCode, "2", "", "");
					return null;
				}

			} else {
				LOG.info("请求查询订单失败======");
				return null;
			}

		} catch (IOException e) {
			e.printStackTrace();
			LOG.error(ExceptionUtil.errInfo(e));
			return null;
		}

		return null;
	}

	private static String hmacSign() {
		StringBuilder hmacStr = new StringBuilder();
		for (NameValuePair nameValuePair : param2) {
			if (nameValuePair.getName().equals("hmac")) {
				continue;
			}
			hmacStr.append(nameValuePair.getValue() == null ? "" : nameValuePair.getValue());

		}

		String hmac = Digest.hmacSign(hmacStr.toString(),
				"hf6Kjql0340f2769N82CCAlj0k23570W2uGP8Z2V4qeF9Z2B941hmio7K65w");

		return hmac;
	}

	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/transactionclear/query/ordercode/ybquickqwe")
	public @ResponseBody Object queryOrderCodeYBQuickqwe(HttpServletRequest request) {
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +1);
		date = calendar.getTime();

		Date date1 = new Date();
		Calendar calendar1 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar1.add(Calendar.DAY_OF_MONTH, -1);
		date1 = calendar1.getTime();

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Date date2 = new Date();
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(date2);
		calendar2.add(Calendar.MINUTE, -5);
		date2 = calendar2.getTime();
		
		
		LOG.info("====" + sdf.format(date));
		LOG.info("====" + sdf.format(date1));
		LOG.info("====" + sdf1.format(date2));

		String[] strings = { "XJY_QUICK1", "LF_QUICK", "SDJ_QUICK", "CJ_QUICK", "YB_QUICK", "YB_PAY" };

		List<PaymentOrder> list = paymentOrderBusiness.findOrderByTimeAndChannelTagAndStatus(sdf.format(date1),
				sdf1.format(date2), strings, "0", "");

		LOG.info("需要改成 已取消的=============" + list.size());
		
		
		return null;
	}
	
	
}
